我希望实现一个锁机制,这样只有一个线程可以运行一个代码块。但是我不希望其他线程在锁对象上等待,如果锁定了,它们就不应该做任何事情。所以这和标准的锁机制有点不同。
if (block is not locked)
{
// Do something
}
else
{
// Do nothing
}在C#中实现这一目的的最佳方法是什么。
发布于 2014-04-01 20:54:26
然后,您应该使用班级,而不是使用锁。
摘录: 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;
}正如马克·格雷维尔所指出的,waitTime也可以选择为零。根据不同的场景,10 on或100 on可能更有效。
发布于 2014-04-01 20:54:24
使用Monitor.TryEnter( lockObject, timespan) {..。}
https://stackoverflow.com/questions/22796630
复制相似问题