C# 简易秒杀场景

 新建队列操作类


    public class TreadingMS
    {
        public static Queue Pall = new Queue();
        public static Queue Pget = new Queue();
        public static int CarNum = 100;
        public MsgReturn mr = new MsgReturn();
        public ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
        public TreadingMS() {
            RunDequeue();
        }

        delegate void cc();
        public static void RunDequeue()
        {
            Task.Factory.StartNew(()=> {
                while (true)
                {
                    Dequeue();
                }
            });
        }

        public static void Dequeue()
        {
            while (true) {
                if (Pget.Count != 0)
                {
                    string uname = Pget.Dequeue().Uname;
                    File.AppendAllText(@"E:\2.txt", uname + "抢购成功"+System.Environment.NewLine);
                }
            }
        }
        int i = CarNum;
        public MsgReturn GetCar(Car c)
        {

            Pall.Enqueue(c);
            if (Pall.Count > CarNum)
                return
 new MsgReturn() { msg = c.Uname + "很遗憾未抢到,车辆已经被抢购一空。", IsOk = false, Rnum = 0 };
            Pget.Enqueue(c);
            i -= 1;
            mr = new MsgReturn()
            {
                msg = "恭喜" + c.Uname + ",抢购QQ一辆。",
                IsOk = true,
                Rnum = i
            };
            return mr;
        }
        public class Car
        {
            public string Uname { get; set; }            
        }

        public class MsgReturn
        {
            public string msg { get; set; }
            public int Rnum { get; set; }
            public bool IsOk { get; set; }
        }
    }

控制器操作

public ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
        public ActionResult GetCarOnline(TreadingMS.Car getPerson)
        {
            TreadingMS ms = new TreadingMS();             
            Parallel.For(0, 1000,i=> {               
                //写独占锁
                cacheLock.EnterWriteLock();
                try
                {
                    ms.mr = ms.GetCar(getPerson);
                    File.AppendAllText(@"E:\3.txt", ms.mr.msg + " 剩余车辆数:" + ms.mr.Rnum + System.Environment.NewLine);
                }
                finally
                {
                    cacheLock.ExitWriteLock();
                }                            
                
            });
              
           return View();
               
        }

模拟操作中 使用了多线程锁  

 

C# 简易秒杀场景_第1张图片

你可能感兴趣的:(C# 简易秒杀场景)