如何从另一个线程锁定方法的一部分? [英] How to lock a part of method from another threads?

查看:63
本文介绍了如何从另一个线程锁定方法的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从另一个线程锁定c#中的一部分方法? 我的意思是,如果其中一个线程在这里,请退出... 例如:

How can i lock a part of method in c# from another threads? I mean if one of threads was here, then exit... For example:

if(threads[0].WasHere)
{
   return;
}

推荐答案

一种有效的方法是使用互锁的交换.通过在工作期间将某些标记字段设置为非默认值,其他线程可以检查并退出.例如:

an effective way is with an interlocked exchange; by setting some token field to a non-default value during the work, the other threads can check this and exit. For example:

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   
}

这篇关于如何从另一个线程锁定方法的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆