一,队列的实现
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace bingfa{ class Program { //实例引用类型的私有对象,用来实现锁的操作,当这个对象释放,下一个才可以调用锁住的方法 private static object o = new object(); static void Main(string[] args) { //开启线程监听 UserHelper.Instance.Start(); //实现多并发 Task t1 = Task.Factory.StartNew(() => { AddUser(); }); Task t2 = Task.Factory.StartNew(() => { AddUser(); }); Task.WaitAll(t1, t2); Console.ReadKey(); } //集合数据添加操作 static void AddUser() { Parallel.For(0, 10, (i) => { lock (o) // 添加锁,避免丢失 { UserHelper.Instance.AddQueue("Name" + i); } }); } } //队列临时类 public class UserInfo { public string Name { get; set; } } public class UserHelper { #region 使用队列和锁,实现当多并发是出现的请求丢失 public readonly static UserHelper Instance = new UserHelper(); private UserHelper() { } private QueueLQueue = new Queue (); public void AddQueue(string Name) //入列 { UserInfo qinfo = new UserInfo(); qinfo.Name = Name; LQueue.Enqueue(qinfo); } public void Start()//启动线程 { Thread thread = new Thread(threadStart); thread.IsBackground = true; thread.Start(); } private void threadStart() //现成监听方法 { while (true) { if (LQueue.Count > 0) { try { ShowQueue(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } else { //没有任务,休息3秒钟 Thread.Sleep(3000); } } } //执行的方法,即是当有对象进入队列的实现方法 private void ShowQueue() { while (LQueue.Count > 0) { try { //从队列中取出数据进行操作 UserInfo qinfo = LQueue.Dequeue(); Console.WriteLine(qinfo.Name); } catch (Exception ex) { throw; } } } #endregion }}