制片人/消费者线程

时间:2015-09-16 03:55:46

标签: c# multithreading c#-4.0 thread-safety threadpool

我想生产一件商品而只消费那件商品。这里的目标是使用CountdownEvent。任何人都可以告诉我这里我做错了什么,我怎样才能改进这个例子来使这个工作?贝娄我正在添加代码

class Program
{
    private static int counter = 1;
    static Queue<Product> products = new Queue<Product>();
    static readonly object locker = new object();
    static CountdownEvent countdown = new CountdownEvent(1);

    static void Main(string[] args)
    {
        Task.Run(() => Producer());
        Task.Run(() => Consumer());

        Console.ReadLine();
    }

    static void Producer()
    {
        while (true)
        {
            var product = new Product()
            {
                Number = counter,
                Name = "Product " + counter++
            };

            lock (locker)
            {
                //Adding one element
                Console.WriteLine("Producing: " + product);
                products.Enqueue(product);

                countdown.Wait();
            }

            Thread.Sleep(500);
        }
    }

    static void Consumer()
    {
        while (true)
        {
            lock (locker)
            {
                //wait until exist one element
                if (!products.Any())
                  continue;

                var product = products.Dequeue();
                Console.WriteLine("Consuming: " + product);
                countdown.Signal();
            }

            Thread.Sleep(500);
        }
    }
}

public class Product
{
    public int Number { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
        return Name;
    }
}

0 个答案:

没有答案