C#排队处理DEMO
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace TestWait { class Program { public static Queue<Proccess> QueueMessage = new Queue<Proccess>(); static int count = 15;//只有15张票 static void Main(string[] args) { StartProccess(); //模拟并发 20个人同时买票 for (int i = 0; i < 20; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback ((o)=>{ string index = (string)o; Bay(index); }),"客户端"+i); } Console.ReadKey(); } //购买服务 static bool Bay(String val) { Proccess p = new Proccess(); p.val = val; p.ManualReset = new ManualResetEvent(false); //lock (QueueMessage) { QueueMessage.Enqueue(p);//消息入列 Console.WriteLine("入列:" + val); } WaitHandle.WaitAll(new WaitHandle[] { p.ManualReset });//等待处理完成 return p.Result; } //启动处理线程 static void StartProccess() { ThreadPool.QueueUserWorkItem(new WaitCallback(ProccessThread)); } //处理线程 static void ProccessThread(Object obj) { while (true) { if (QueueMessage.Count > 0) { Proccess message = QueueMessage.Dequeue(); if (count <= 0) { message.Result = false; Console.WriteLine("处理失败:" + message.val); } else { message.Result = true; Console.WriteLine("处理成功:" + message.val); } count--; if (message.ManualReset != null) message.ManualReset.Set(); } else { //如果没有消息 停止3s Thread.Sleep(3000); } } } } class Proccess{ public ManualResetEvent ManualReset { get; set; } public bool Result { get; set; } public String val { get; set; } } }