我想知道如何在执行线程内部做线程安全的,让我通过例子来解释一下:
假设我想要一个命令管道,这些命令应该一个接一个地连续执行,但是在我的线程中我等不及它们了。线程通常处于休眠状态,如果某个命令入队则被唤醒,然后它执行队列中的所有命令并再次进入休眠模式,直到新命令入队。类似于:
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/