Using locks inside a loop

Posted by Xaqron on Stack Overflow See other posts from Stack Overflow or by Xaqron
Published on 2011-01-08T11:27:22Z Indexed on 2011/01/08 11:53 UTC
Read the original article Hit count: 190

Filed under:
|
|
// Member Variable
private readonly object _syncLock = new object();

// Now inside a static method

foreach (var lazyObject in plugins)
{
   if ((string)lazyObject.Metadata["key"] = "something")
   {
      lock (_syncLock)
      {
         if (!lazyObject.IsValueCreated)
            lazyObject.value.DoSomething();
      }
      return lazyObject.value;
   }
}

Here I need synchronized access per loop. There are many threads iterating this loop and based on the key they are looking for, a lazy instance is created and returned.

lazyObject should not be created more that one time. Although Lazy class is for doing so and despite of the used lock, under high threading I have more than one instance created (I track this with a Interlocked.Increment on a volatile shared int and log it somewhere). The problem is I don't have access to definition of Lazy and MEF defines how the Lazy class create objects.

My questions: 1) Why the lock doesn't work ?

2) Should I use an array of locks instead of one lock for performance improvement ?

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading