Hashtable to Dictionary<> syncroot .

扶醉桌前 提交于 2019-11-27 14:45:51

If you are going strictly for compatability then Bryan is correct. This is the best way to maintain your current semantics on top of a Dictionary.

Expanding on it though. The reason the SyncRoot property was not directly added to the generic dictionary is that it's a dangerous way to do synchronization. It's only slighly better than "lock(this)" which is very dangerous and prone to deadlocks. Here are a couple of links that speak to why this is bad.

The new thinking behind SyncRoot is that it was a mistake in the original design. If the only thing to lock is the dictionary and it's private, you can lock it or another object that serves as the synchronization object. The latter technique is useful when the state you are protecting is more than just the dictionary.

// used as you would have used SyncRoot before
object _syncLock = new object();
Dictionary<string, int> numberMapper = new Dictionary<string, int>();

// in some method...
lock (_syncLock)
{
    // use the dictionary here.
}
var dictionary = new Dictionary<int, string>();

lock(((ICollection) dictionary).SyncRoot)
{
    // ...
}

If the hashtable/dictionary isn't public, you could just lock the dictionary object itself.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!