c#中的锁定机制

pen*_*uru 1 c# multithreading mutex semaphore

我想实现一个锁机制,所以只有一个线程可以运行一个代码块.但我不希望其他线程等待锁定对象,如果它被锁定,它们应该什么都不做.所以它与标准锁机制略有不同.

if (block is not locked)
{
    // Do something
}
else
{
    // Do nothing
}
Run Code Online (Sandbox Code Playgroud)

在C#中执行此操作的最佳方法是什么?

Eri*_*ips 9

然后,您应该使用MonitorClass,而不是使用锁.

摘录:来自MSDN的Monitor.TryEnter()示例

// 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;
}
Run Code Online (Sandbox Code Playgroud)

正如Marc Gravell所说,waitTime可以选择为零.根据不同的情况,10ms或100ms可能更有效.

  • 作为旁注:如果OP不想要任何等待,`waitTime`*可以为零* (3认同)