Ejemplo n.º 1
0
        static async Task Test()
        {
            var conn  = ConnectionMultiplexer.Connect("192.168.50.100");
            var redis = conn.GetDatabase();


            var tasks = new List <Task>();


            for (int i = 0; i < 10; i++)
            {
                var t = Task.Run(async() =>
                {
                    var rlock = new RedisMutexLock(conn, "locktest");
                    //Console.WriteLine($"开始执行{i}");
                    await rlock.TryAcquireAsync(0);
                    Console.WriteLine("加锁成功");

                    //await Task.Delay(2000);

                    await rlock.ReleaseAsync();
                    Console.WriteLine("解锁成功");
                });
                tasks.Add(t);
            }

            await Task.WhenAll(tasks);
        }
Ejemplo n.º 2
0
        public async Task Should_be_order()
        {
            _redis.StringSet("count", 5);

            await CreateParallelTask(10, async() =>
            {
                var rlock = new RedisMutexLock(_conn, "locktest");
                await rlock.TryAcquireAsync(0);

                await DeductInventory();

                await rlock.ReleaseAsync();
            });

            var count = _redis.StringGet("count").ToString();

            Assert.Equal("0", count);
        }
Ejemplo n.º 3
0
        static async Task LockTest()
        {
            var conn  = ConnectionMultiplexer.Connect("192.168.50.100");
            var redis = conn.GetDatabase();

            redis.StringSet("count", 50);
            var tasks = new List <Task>();

            for (int i = 0; i < 100; i++)
            {
                var t = Task.Run(async() =>
                {
                    var rlock = new RedisMutexLock(conn, "locktest");
                    await rlock.TryAcquireAsync(0);
                    Console.WriteLine($"线程{Thread.CurrentThread.ManagedThreadId}获取锁");
                    var val   = redis.StringGet("count");
                    var count = int.Parse(val.ToString());

                    //await Task.Delay(500);
                    if (count > 0)
                    {
                        redis.StringIncrement("count", -1);
                    }

                    await rlock.ReleaseAsync();
                    Console.WriteLine($"线程{Thread.CurrentThread.ManagedThreadId}释放锁");
                });
                tasks.Add(t);
            }

            await Task.WhenAll(tasks);

            Console.WriteLine("=====================");
            Console.WriteLine(redis.StringGet("count"));

            Console.ReadKey();
        }