通过锁字符串达到控制并发的效果C#

转自:https://www.cnblogs.com/hnsongbiao/p/8926086.html

场景:高并发情况下在程序内给每张数据表自动生成id

思路:很容易想到当后台接受到请求的时候就用一把锁住,然后在锁里面进行id自增。但是在高并发的情况下只用一把锁不太适合,理想的做法是每张表有一把锁。那么怎么给每张表设置一把锁呢,你可以为每张表生成一个object对象并保存起来,然后将object对象做为锁,那么有没有更简单的方法呢,比如说直接用表名做锁。表名是一个字符串,那么它可不可以做为锁呢,确定的说是可以的,.net内部会把相同的字符串作为同一个内部对象(运算得到的字符串不受影响,只要你不是new string),下面的代码实验使用字符串做为锁的效果。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> keyList = new List<string> { "key1", "key2", "key" + "1", "ke" + "y1", "key1", "key1", };

            keyList.ForEach(u =>
            {
                ThreadPool.QueueUserWorkItem(s =>
                {
                    test.lockTestByString(u);
                });

            });
            Console.ReadLine();
        }
    }
    public class test
    {

        public static void lockTestByString(string key)
        {
            lock (key)
            {
                Console.WriteLine("上锁2s key=" + key);
                Thread.Sleep(2000);
                Console.WriteLine("解锁");

            }
        }

    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp3
{
    class Program2
    {
        static void Main(string[] args)
        {
            List<string> keyList = new List<string> { new string('k', 1), new string('k', 1), new string('k', 1), new string('k', 1) };

            keyList.ForEach(u =>
            {
                ThreadPool.QueueUserWorkItem(s =>
                {
                    test.lockTestByString(u);
                });

            });
            Console.ReadLine();
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class test2
    {

        public static void lockTestByString(string key)
        {
            lock (key)
            {
                Console.WriteLine("上锁2s key=" + key);
                Thread.Sleep(2000);
                Console.WriteLine("解锁");

            }
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值