Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.NET消费者/生产者(队列)_.net_Locking_Queue_Consumer_Producer - Fatal编程技术网

.NET消费者/生产者(队列)

.NET消费者/生产者(队列),.net,locking,queue,consumer,producer,.net,Locking,Queue,Consumer,Producer,我是.NET/Threads的新手,我想知道是否有人能在这个练习上帮助我。我需要替换注释,以使其在不锁定线程的情况下工作: private Queue<int> queue; public void ConsumeFunc(){ while (true){ // 1 while (/* 2 */){ // 3 } int element = queue.Dequeue(); //

我是.NET/Threads的新手,我想知道是否有人能在这个练习上帮助我。我需要替换注释,以使其在不锁定线程的情况下工作:

private Queue<int> queue;

public void ConsumeFunc(){
    while (true){
        // 1
        while (/* 2 */){
        // 3
        }
        int element = queue.Dequeue();
        // 4
        Console.WriteLine("Consume element: " + element);
        Thread.Sleep(new Random((int)DateTime.Now.Ticks).Next(0, 2) * 1000);
    }
}

private void ProduceFunc(){
    while (true) {
        // 1
        queue.Enqueue(DateTime.Now.Millisecond);
        // 2
        // 3
        Thread.Sleep(new Random((int)DateTime.Now.Ticks).Next(0, 2) * 1000);
    }
}
并给出以下错误: 从未同步的代码块调用了对象同步方法
Monitor.pulsell(队列)上

与其自己努力实现同步,不如看一看。它为您处理所有的同步,并且将比您使用
队列
类和
监视器
创建的任何东西都表现得更好


NET文档中有大量关于堆栈溢出的示例,以及其他地方的示例。您可能会发现我的文章很有用:

+1用于在请求帮助之前演示解决问题的方法。问得真干净利落!如果目标是构建队列,那么您最好使用ConcurrentQueue:@Mathias:
BlockingCollection
是一个更通用的接口,默认情况下,它使用
ConcurrentQueue
作为其后备存储。我还没有遇到过这样的情况:最好单独使用
ConcurrentQueue
public void ConsumerFunc(){
    while (true){
        Monitor.PulseAll(queue);    // 1
        while (queue.Count == 0){   /* 2 */
            Monitor.Wait(queue);    // 3
        }
        int element = queue.Dequeue();
        lock (queue)    // 4
        Console.WriteLine("Consume element: " + element);
        Thread.Sleep(new Random((int)DateTime.Now.Ticks).Next(0, 2) * 1000);
    }
}


public void ProducerFunc(){
    while (true) {
        lock (queue)    // 1
        queue.Enqueue(DateTime.Now.Millisecond);
        Monitor.PulseAll(queue);    // 2
        // 3 ???
        Thread.Sleep(new Random((int)DateTime.Now.Ticks).Next(0, 3) * 1000);
    }
}