加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何确保只有一个线程会做某事?

发布时间:2020-12-15 18:02:10 所属栏目:百科 来源:网络整理
导读:我有多个线程将项目添加到无锁队列. 然后这些项目被另一个线程处理. 在制作人员线程中,我需要启动消费者线程,但只有当它没有运行或启动时才会启动. 特别: public void BeginInvoke(Action method){ //This runs on multiple background threads pendingActi
我有多个线程将项目添加到无锁队列.
然后这些项目被另一个线程处理.

在制作人员线程中,我需要启动消费者线程,但只有当它没有运行或启动时才会启动.

特别:

public void BeginInvoke(Action method)
{
    //This runs on multiple background threads
    pendingActions.Enqueue(method);
    if (ProcessQueue hasn't been posted)
        uiContext.Post(ProcessQueue,null);
}
private void ProcessQueue(object unused)
{
    //This runs on the UI thread.
    Action current;
    while (pendingActions.TryDequeue(out current))
        current();
}

我正在使用.Net 3.5,而不是4.0.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读