3

我是 .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);
    }
}

我管理了这个,但它没有完成

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);
    }
}

并给出以下错误: 对象同步方法是从不同步的代码块中调用的,在Monitor.PulseAll(queue);

4

1 回答 1

1

与其努力自己实现同步,不如看看BlockingCollection。它为您处理所有同步,并且比您使用Queue类和Monitor.

There are plenty of examples in the .NET documentation, here on Stack Overflow, and elsewhere. You might find my article useful: http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=821

于 2011-12-27T00:59:39.660 回答