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.