我如何从另一个线程锁定c#中的一部分方法?我的意思是,如果其中一个线程在这里,则退出...例如:
if(threads[0].WasHere)
{
return;
}
一种有效的方式是使用互锁的交换机。通过在工作期间将某些标记字段设置为非默认值,其他线程可以检查并退出。例如:
private int hazWorker; // = 0 - put this at the scope you want to protect
然后:
// means: atomically set hazWorker to 1, but only if the old value was 0, and
// tell me what the old value was (and compare that result to 0)
if(Interlocked.CompareExchange(ref hazWorker, 1, 0) != 0) {
return; // someone else has the conch
}
try {
// your work here
} finally {
Interlocked.Exchange(ref hazWorker, 0); // set it back to default
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句