c# - thread worker 内部线程安全

标签 c# synchronization thread-safety

我想知道如何在执行线程内部做线程安全的,让我通过例子来解释一下:

假设我想要一个命令管道,这些命令应该一个接一个地连续执行,但是在我的线程中我等不及它们了。线程通常处于休眠状态,如果某个命令入队则被唤醒,然后它执行队列中的所有命令并再次进入休眠模式,直到新命令入队。类似于:


public void Enqueue(ICommand command)
{
    this.queue.Enqueue(command);
    this.synchroHandler.Set();
}

private void Pipeline()
{
    while (true)
    {
        this.synchroHandler.WaitOne();

        while (this.queue.Count > 0)
        {
            ICommand command = this.queue.Dequeue();
            command.Execute();
        }
        // what if command will be enqueued between previous command - HERE

        // ... and this command HERE
        this.synchroHandler.Reset();
    }
}

public void Main()
{
    this.queue = new ThreadSafeQueue<ICommand>();
    this.computionHandler = new ManualResetEvent(false);
    Thread thread = new Thread(new ThreadStart(this.Pipeline));
    thread.Start();

    // start adding commands to pipeline
    this.Enqueue(command1);
    this.Enqueue(command2);
    ...
}

假设我的队列实现是线程安全的,所以 this.queue.Count、this.queue.Enqueue 和 this.queue.Dequeue 使用相同的锁。如果 public Enqueue() 将在“}”和 this.synchroHandler.Reset() 之间被调用,则示例中显示的 Ss;即使队列中只有一个项目,线程也会最终进入休眠状态(this.synchroHandler.Set() 将在 this.synchroHandler.Reset() 之前调用)。知道如何使这个架构线程安全吗?

最佳答案

查看 BlockingCollection <T> , 线程安全的生产者-消费者 System.Collections.Concurrent命名空间。

关于c# - thread worker 内部线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4126739/

相关文章:

java - 以一种有效的方式使用 ByteBuffer 将 header 和数据布局打包在一个字节数组中?

c# - 哪种方式最适合线程同步?

c# - UPDATE子句中的集合列表中的错误。无法解析查询文本

linux - 当所有 N 个进程都位于临界区内时,信号量实际上如何工作?

android - 将 Android 手机与 ASP.net MVC 4 应用程序连接的 Web 服务

javascript - Kendo UI 数据源sync() 将不起作用

scala - Scala对象和线程安全

c# - 我可以在 IIS 之外托管 ASP.NET 网站吗?

c# - 在这种特定情况下,我应该如何建模我的代码以最大限度地重用代码?

c# - 电子 token 证书的签名和验证