下面的代码不能使用自动重置事件,我在做什么错误?生产者消费者使用c#中的AutoReset事件#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Threaddd
{
class Program
{
static int num = 0;
static EventWaitHandle e = new AutoResetEvent(false);
static object o = new object();
static void Main(string[] args)
{
new Thread(Consumer).Start();
new Thread(Producer).Start();
}
static void Producer()
{
while (true)
{
if (num == 0)
{
num++;
Console.WriteLine("Produced " + num);
Thread.Sleep(1000);
e.Set();
e.WaitOne();
}
}
}
static void Consumer()
{
while (true)
{
if (num == 1)
{
Console.WriteLine("Consumed " + num);
Thread.Sleep(1000);
num--;
e.Set();
e.WaitOne();
}
else
{
e.WaitOne();
}
}
}
}
如果您能告诉我们您期望代码执行的内容,它总是有帮助的。 –
作为一个旁注,如果您使用的是.NET 4,那么会有使数据结构更加简单的数据结构,其中一个是BlockingCollection http://msdn.microsoft.com/zh-cn/library/dd267312.aspx – PeskyGnat
当Semaphore可用时使用AutoResetEvent。 –