c# - Lock and do all work, or release and grab only when necessary? -
which of these 2 alternatives better one? locking outside loops? lock (_worklock) { foreach (var resultobject in getobjecttask.result) { foreach (var key in resultobject.keys) { string value = resultobject.getvalue(key); _lockedobject.dosomething(key, value); } } } or locking when locked object accessed? foreach (var resultobject in getobjecttask.result) { foreach (var key in resultobject.keys) { string value = resultobject.getvalue(key); lock (_worklock) _lockedobject.dosomething(key, value); } } there can potentially 5-10 simultaneous operations wanting @ same time. here's surrounding code: var tasks = provider in _objectproviders select task.factory.startnew(() => provider.objects) .continuewith(getobjecttask => { // 1 of operation bodies above go here }); var tasklist = task.whenall(tasks); tasklist.wait(); // us...