Thread safety with Dictionary in .Net

后端 未结 4 1422
盖世英雄少女心
盖世英雄少女心 2020-12-19 03:15

I have this function:

static Dictionary KeyValueDictionary = new Dictionary();
static void IncreaseValue(int keyId, int adj         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-19 04:19

    The .NET library has a thread safe dictionary, the ConcurrentDictionary http://msdn.microsoft.com/en-us/library/dd287191.aspx

    Updated: I didn't exactly answer the question, so here's updated with more answery to exact question posed. As per the MSDN:http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

    A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

    For a thread-safe alternative, see ConcurrentDictionary.

    Public static (Shared in Visual Basic) members of this type are thread safe.

提交回复
热议问题