C# 简易秒杀场景

 新建队列操作类


    public class TreadingMS
    {
        public static Queue<Car> Pall = new Queue<Car>();
        public static Queue<Car> Pget = new Queue<Car>();
        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();
               
        }

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值