是锁定字典查找所必需的吗? [英] is locking necessary for Dictionary lookup?

查看:137
本文介绍了是锁定字典查找所必需的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ {code $ lock $($)
{
dictionaryX.TryGetValue(key,out value);
}

在对字典进行查找时锁定必需?



该程序是多线程的,同时向dict添加键/值。 dict被锁定。

解决方案

只有当您在线程之间同步资源访问时,才需要锁定。只要不涉及多个线程,那么在这里不需要锁定。



在更新和读取多个线程的值的上下文中,是一个锁是绝对必要的。事实上,如果你使用4.0,你应该考虑切换到专门为并发访问而设计的集合之一。


lock(dictionaryX)
{
   dictionaryX.TryGetValue(key, out value);
}

is locking necessary while doing lookups to a Dictionary ?

THe program is multithreaded, and while adding key/value to dict. dict is being locked.

解决方案

Locking is only needed when you are synchronizing access to a resource between threads. As long as there are not mulitple threads involved then locking is not needed here.

In the context of updating and reading the value from multiple threads, yes a lock is absolutely necessary. In fact if you're using 4.0 you should consider switching to one of the collections specifically designed for concurrent access.

这篇关于是锁定字典查找所必需的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆