111,097
社区成员




private static Dictionary<string,int> typeData = new Dictionary<string,int>();
private static object lockHelper = new object();
static void Work(string typeKey)
{
lock(lockHelper){
//执行一些相同的操作,比如
typeData[typeKey] = typeData[typeKey] + 3;
}
}
private static Dictionary<string,int> typeData = new Dictionary<string,int>();
private static Dictionary<string, object> lockHelper = new Dictionary<string, object>();
static void Work(string typeKey)
{
lock(lockHelper[typeKey]){ //lockHelper[typeKey]是确定存在且已经初始化了的 lockHelper[typeKey] = new object();
//执行一些相同的操作,比如
typeData[typeKey] = typeData[typeKey] + 3;
}
}
public static class Demo
{
private static Dictionary<string, int> typeData = new Dictionary<string, int>();
private static Dictionary<string, object> lockHelper = new Dictionary<string, object>();
static Demo()
{
List<string> configData = new List<string>() { "test1", "test2" }; //从配置文件中获取的,运行时项不会有变动
foreach (var data in configData)
{
typeData.Add(data, 0);
lockHelper.Add(data, new object());
}
}
static void Work(string typeKey)
{
if (typeData.ContainsKey(typeKey) == false) return;
lock (lockHelper[typeKey])
{
//执行一些相同的操作,比如
typeData[typeKey] = typeData[typeKey] + 3;
}
}
}