您现在的位置是:网站首页> C#技术
通过锁字符串达到控制并发的效果C#
- C#技术
- 2021-05-22
- 795人已阅读
通过锁字符串达到控制并发的效果C#
而.net有内部机制使得相同的字符串内存地址是相同的(new string)除外
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
List<string> keyList = new List<string> { "key1", "key2", "key1", "key1", "key1", "key1", };
keyList.ForEach(u =>
{
ThreadPool.QueueUserWorkItem(s =>
{
Test.lockTestByString(u);
});
});
Console.Read();
}
}
public class Test
{
public static void lockTestByString(string key)
{
lock (key)
{
GCHandle handle = GCHandle.Alloc(key, GCHandleType.Pinned);
//获取内存地址
IntPtr address = handle.AddrOfPinnedObject();
Console.WriteLine("上锁2s key=" + key + " 内存地址:" + address);
Thread.Sleep(2000);
Console.WriteLine("解锁");
}
}
}
}
上一篇:MyCat使用技术收集
下一篇:让ASP.NET站点暂停