multithreading - Thread safe Increment in C# -


i trying increment element in list in c#, need thread safe, count not affected.

i know can integers:

interlocked.increment(ref sdmpobjectlist1count);

but not work on list have following far:

lock (padlock) {      differencelist[diff[d].propertyname] = differencelist[diff[d].propertyname] + 1; } 

i know works, i'm not sure if there way this?

as david heffernan said, concurrentdictionary should provider better performance. but, performance gain might negligible depending upon how multiple threads try access cache.

using system; using system.collections.concurrent; using system.threading;  namespace concurrentcollections {     class program     {         static void main()         {             var cache = new concurrentdictionary<string, int>();              (int threadid = 0; threadid < 2; threadid++)             {                 new thread(                     () =>                     {                         while (true)                         {                             var newvalue = cache.addorupdate("key", 0, (key, value) => value + 1);                             console.writeline("thread {0} incremented value {1}",                                 thread.currentthread.managedthreadid, newvalue);                         }                      }).start();             }              thread.sleep(timespan.fromminutes(2));         }     } } 

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -