Thread safety with Dictionary in .Net

后端 未结 4 1416
盖世英雄少女心
盖世英雄少女心 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:14

    You've just been lucky so far. It's not thread-safe.

    From the Dictionary documentation...

    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.

提交回复
热议问题