thread safety - C# Thead-Safe collection in Object -


this example code illustrate question.

assume have following class:

enter code here using system; using system.collections.generic; using system.linq; using system.text; using system.collections.concurrent;   namespace boxesa4 { class box {     public double length { get; set; }     public double width { get; set; }     public double height { get; set; }  concurrentdictionary<int, string> boxitems = new concurrentdictionary<int, string>();       public box(double length,double width,double height)     {         this.length=length;         this.width = width;         this.height = height;      }      public double volume()     {         return this.length * this.width * this.height;     }      public void add(int index,string item)     {         boxitems.tryadd(index, item);      }        } } 

main:

    static void main(string[] args)     {        box createbox = new box(10,10,5,5);        createbox.add(0,"hammer");        createbox.add(1,"saw");      } 

in main method calling createbox.add(); , passing necessary arguments. have worry thread-safety when comes calling add method? i don't want make box class static. if thread-safety issue how go fixing code?

assuming behaviour of concurrentdictionary.tryadd meets requirements, you're fine. you'd in better position if made boxitems field read-only.

it's worth reading docs in detail when use concurrent collections, see can happen. example, may want addorupdate instead of tryadd - want happen if key exists in dictionary?


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -