Pregunta

I want to implement a lock mechanism so only one thread can run a block of code. But I don't want other threads to wait on lock object, they should do nothing if it's locked. So it's a little different than standard lock mechanism.

if (block is not locked)
{
    // Do something
}
else
{
    // Do nothing
}

What is the best way to do this in C#.

¿Fue útil?

Solución

Then instead of using locks, you should use the Monitor Class.

Excerpt: Monitor.TryEnter() example from MSDN

// Request the lock. 
if (Monitor.TryEnter(m_inputQueue, waitTime))
{
   try
   {
      m_inputQueue.Enqueue(qValue);
   }
   finally
   {
      // Ensure that the lock is released.
      Monitor.Exit(m_inputQueue);
   }
   return true;
}
else
{
   return false;
}

As Marc Gravell noted, waitTime can optionally be zero. Depending on different scenarios 10ms or 100ms might be more effective.

Otros consejos

use Monitor.TryEnter( lockObject, timespan) { .... }

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top