gpt4 book ai didi

c# - 在同一个线程中锁定字典

转载 作者:可可西里 更新时间:2023-11-01 09:05:52 24 4
gpt4 key购买 nike

我有一个函数,它根据键(名称)返回字典中的一个条目,如果它不存在,则返回一个新创建的条目。

我的问题是“双锁”:SomeFunction 锁定 _dictionary,检查键是否存在,然后调用一个也锁定同一个字典的函数,它似乎工作但我不确定是否这种方法存在潜在问题。

public Machine SomeFunction(string name) 
{
lock (_dictionary)
{
if (!_dictionary.ContainsKey(name))
return CreateMachine(name);
return _dictionary[name];
}
}


private Machine CreateMachine(string name)
{
MachineSetup ms = new Machine(name);
lock(_dictionary)
{
_ictionary.Add(name, ms);
}
return vm;
}

最佳答案

这保证有效 - 锁在 .NET 中是递归的。这是否真的是个好主意是另一回事……这个怎么样:

public Machine SomeFunction(string name) 
{
lock (_dictionary)
{
Machine result;
if (!_dictionary.TryGetValue(name, out result))
{
result = CreateMachine(name);
_dictionary[name] = result;
}
return result;
}
}

// This is now *just* responsible for creating the machine,
// not for maintaining the dictionary. The dictionary manipulation
// is confined to the above method.
private Machine CreateMachine(string name)
{
return new Machine(name);
}

关于c# - 在同一个线程中锁定字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2411786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com