c# - lock keyword on a LINQ Parallel.ForEach<> loop -


This is a conceptual question. I was thinking that if I used a lock inside Parallel.ForEach do & lt; & Gt; The loop will take away the benefits of a paragraph foreach loop.

Here is some sample code where I have done this.

  Parallel.ForEach & LT; KeyValuePair & LT; String, XElement & gt; & Gt; (BinReferences.KeyValuePairs, Reference => {LockLockObject} {if (fileLocks.ContainsKey (reference.Key) == false) {fileLocks.Add (reference.Key, new object ());}} RecursiveBinUpdate (reference .value, testpath, reference.key, maxRecursionCount, referee recursionCount; lock (fileLocks [reference.Key]) {reference.Value.doc.sev (reference);}});  

Where fileLockObject and fileLocks are as follows

  Private static object file LockObject = new object (); Private Stable Dictionary & lt; String, Object & gt; FileLocks = New Dictionary & lt; String, Object & gt; ();  

Does this technique not completely parallel the loop? I want to see my thoughts on this.

This means that lock can not be done in parallel. It hurts the performance here too, yes. Since the entire body is not all locked (and lock on the same object) still there is some parallel here. Whether it is that you get over the top of the land that comes with the management of threads and synchronizing around the locks, there is enough support to overcome something you really just have to test yourself with your specific data Need for

As stated, it looks like what you are doing (locking at least the first locked block on which I am more worried on each thread, on the same object ) A dictionary . You can instead use any ConcurrentDictionary , which is specifically designed to be used by more threads, and the amount of synchronization that should be reduced will be done.


Comments

Popular posts from this blog

ios - How do I use CFArrayRef in Swift? -

eclipse plugin - Run java code error: Workspace is closed -

c - Error on building source code in VC 6 -