转自: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("解锁");
}
}
}
}