C# 中的锁定机制
本文关键字:机制 锁定 | 更新日期: 2023-09-27 17:56:07
我想实现一个锁定机制,这样只有一个线程可以运行一个代码块。但我不希望其他线程等待锁定对象,如果它被锁定,它们应该什么都不做。所以它与标准锁定机制略有不同。
if (block is not locked)
{
// Do something
}
else
{
// Do nothing
}
在 C# 中执行此操作的最佳方法是什么?
然后,您应该使用 Monitor
类,而不是使用锁。
摘录:来自 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;
}
正如Marc Gravell所指出的,waitTime
可以选择为零。 根据不同的场景,10ms 或 100ms 可能更有效。
使用 Monitor.TryEnter( lockObject, timespan)
{ .... }