Using per item locks inside a loop
I have a static
method which is accessed by many threads at the same time. For thread-safety collection
this method iterating over would not change is size (no add/no delete). Note that item is a Lazy
object and I don't have access to Lazy
constructor to use the thread-safe one (MEF
do that):
private static readonly object _syncLock = new object();
// Now inside a static method
private static DoSomethingOnItem(string wanted)
{
foreach (var item in items)
{
if (item.Metadata["Name"] = wanted)
{
lock (_syncLock)
item.DoSomething();
}
}
}
Does it boost performance if I use and array of locks
per item or many locks
have much side-effect rather than performa开发者_开发技巧nce boosting ?
private static object[] _syncLocks;
// Code...
_syncLocks = new object[itemsCount]; // in a thread-safe manner
Then inside the loop use each item
specific lock
Why not just lock on the item object, rather than create an array of locks?
I.e.
private static void DoSomethingOnItem(string wanted)
{
foreach (var item in items)
{
if (item.name == wanted)
{
lock (item)
item.DoSomething();
}
}
}
精彩评论