我正在使用ManualResetEvents字典同步一些线程。看上去像这样。我的问题是,像这样调用字典的getter/indexer是否线程安全?应该从锁的上下文调用getter并将值存储在局部变量中吗?
Enum型
enum RecvType
{
Type1,
Type2
//etc...
}ManualResetEvents字典
Dictionary<RecvType, ManualResetEvent> recvSync;等待操作
void WaitForRecv(RecvType recvType, int timeout = 10000)
{
if (!recvSync[recvType].WaitOne(timeout))
{
throw new TimeoutException();
}
// do stuff
}EventHandler (从另一个线程调用)
void RecvDone(object sender, RecvType recvType)
{
recvSync[recvType].Set();
}编辑-澄清字典总数
字典索引
public MyClass()
{
recvSync = new Dictionary<RecvType, ManualResetEvent>();
// populate dictionary (not modified after here)
socketWrapper.RecvDone += RecvDone;
}发布于 2022-02-15 18:24:12
根据文档
只要集合不被修改,
Dictionary<TKey,TValue>可以同时支持多个读取器。
因此,您的使用模式是可以的,关于线程安全。当多个线程正在读取“冻结”Dictionary<K,V>的行为时,定义得很好。
您可以考虑通过使用ImmutableDictionary而不是普通的Dictionary<K,V>来更清楚地表达您的意图,但是这种清晰需要付出代价:在ImmutableDictionary<K,V>中查找元素是~10倍。
https://stackoverflow.com/questions/71129813
复制相似问题