我想实现一个锁机制,所以只有一个线程可以运行一段代码。 但我不希望其他线程等待锁定对象,如果它被锁定,它们应该什么都不做。所以它与标准锁机制略有不同。
if (block is not locked)
{
// Do something
}
else
{
// Do nothing
}
在C#中执行此操作的最佳方法是什么。
答案 0 :(得分:9)
然后,您应该使用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;
}
如Marc Gravell所述,waitTime
可以选择为零。根据不同的情况,10ms或100ms可能更有效。
答案 1 :(得分:0)
使用Monitor.TryEnter( lockObject, timespan)
{....}