c# - 我怎样才能确保只有一个线程会做某事?

标签 c# .net multithreading thread-safety

我有多个线程将项目添加到无锁队列。
然后这些项目由另一个线程处理。

在生产者线程中,我需要启动消费者线程,但前提是它尚未运行或启动

具体来说:

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。 :(

最佳答案

最简单的方法是使用Semaphore。它将计算队列大小。

关于c# - 我怎样才能确保只有一个线程会做某事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6456571/

相关文章:

c# - 使用 X509Certificate2 加载 pfx 文件时为 "An internal error occurred."

c# - 在 iPad 上通过 JavaScript 同步应用程序中的时间

.net - 移动和 .net 网络服务中的加密和解密

c# - 如何在运行时检查动态数据类型的类型?

.net - 将单个元素锁定在静态集合中?

python - 在 Python 中覆盖 threading.excepthook 的正确方法是什么?

c# - C#: Call a method every 5 minutes from a foreach loop

c# - MySQL 连接器打不开

c# - 事件是否在另一个线程中运行? (.Net Compact Framework)

c# - 我应该在这里使用 ref 还是 out 关键字?