现在的位置: 首页 > 综合 > 正文

c# 多线程 生产者/消费者队列 源码

2014年03月02日 ⁄ 综合 ⁄ 共 943字 ⁄ 字号 评论关闭
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
      class Product:IDisposable
    {
        EventWaitHandle EV = new AutoResetEvent(false);
        object ob = new object();
        Queue<string> ppe=new Queue<string>();
        Thread t;
        public Product()
        {
            t = new Thread(new ThreadStart(work));
            t.Start();
        }

        public void SetIn(string ls)
        {
            ppe.Enqueue(ls);
            EV.Set();
        }

        public void Dispose()
        {
            SetIn(null);
            t.Join();
            EV.Close();
        }

        public void work()
        {
            while (true)
            {
                string talk = null;
                lock (ob)
                    if (ppe.Count > 0)
                    {
                        talk = ppe.Dequeue();
                        if (talk == null)
                            return;
                    }
                    
                if (talk != null)
                {
                    Console.WriteLine(talk);
                    Thread.Sleep(1000);
                }
                else
                {
                    EV.WaitOne();
                }
            }
        }
    }

    class rheMain
    {
        static void Main()
        {
            using (Product pt = new Product())
            {
                pt.SetIn("hello!");
                for (int i = 1; i <= 5; i++)
                {
                    pt.SetIn("say:" + i);
                }
                pt.SetIn("good by!");
                 
            }

            //Product pt = new Product();

            //pt.SetIn("hello!");
            //for (int i = 1; i <= 5; i++)
            //{
            //    pt.SetIn("say:" + i);
            //}
            //pt.SetIn("good by!");
            //pt.Dispose();

            Console.WriteLine("oVER!");
            //Console.ReadLine();
        }
    }
}

抱歉!评论已关闭.