简体   繁体   中英

Proper way of using Dictionary

Here I have piece of code, showing example of how I want to update values in dictionary. I do not think this is the best way, because I am not sure that it is thread safe.

Edit: it is just POC code, what I mean is getting Keys copied to array and then doing stuff on Dictionary. I can't post code of my employer here guys, so I made example to make point.

When I get copy of Keys to array, I might be using Dictionary reference in some other part of code, where some keys might be added, and then such function won't update all keys because I have copied those at some point of time. Should I subclass or maybe wrap dictionary and make operations on it with lock, or is there simplier way?

How should I update the values in a proper way?

    static void Main(string[] args)
    {
     Dictionary<string, int> dic = new Dictionary<string, int>();

     dic.Add("Kej1",0);
     dic.Add("Kej2",1);
     dic.Add("Kej3", 3);
     dic.Add("Kej4", 3);

     String[] arr = new string[dic.Count] ;
     dic.Keys.CopyTo(arr,0);

    foreach (var va in arr)
    {
        Console.WriteLine(dic[va] + " " + va);
        dic[va] = 10;
        Console.WriteLine(dic[va] + " " + va);
    }
    Console.ReadKey();
    }

如果您想从.NET 4开始使用Thread Safe字典,则可以使用ConcurrentDictionary

Your current implementation is fine as it is. Your

 Dictionary<string, int> dic = new Dictionary<string, int>(); 

is a local variable and it is only referenced by your main thread. You do not need to worry about thread-safty.

If you really want to make it thread-safe, then you can lock the dictionary this way:

static void Main(string[] args) 
{ 
  Dictionary<string, int> dic = new Dictionary<string, int>(); 

  lock(dic)
  {
   dic.Add("Kej1",0); 
   dic.Add("Kej2",1); 
   dic.Add("Kej3", 3); 
   dic.Add("Kej4", 3); 

   String[] arr = new string[dic.Count] ; 
   dic.Keys.CopyTo(arr,0);

   foreach (var va in arr) 
   { 
     Console.WriteLine(dic[va] + " " + va); 
     dic[va] = 10; 
     Console.WriteLine(dic[va] + " " + va); 
   } 
  } 
  Console.ReadKey(); 
} 

You only need to worry about thread safety if you actually use multiple threads. Most of the time you can't do that unknowingly. So just don't worry about it and access your dictionary any way you want.

If you use anything that has the word "async" or "Begin" in it, you might need to reconsider this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM