Thursday, 15 January 2015

c# - Using yield with concurrent collection -


This is a question coming up from another discussion, though I was curious to know what to do in the following situation while using a concurrent The efficiency of dictionary and yield will be

  IEnumerable & lt; Int & gt; GetValuesNotZero () {foreach (value in dictionary. Value) {if (value! = 0) {yield return value; }}}  

Add / remove / update another thread from the dictionary, so what will happen with the values ​​in the foreach loop? Am I running again on this, or am I running a risk of added / deleted / updated values, even then the dictionary is closed?

When you are repeating it, the dictionary in another thread is modified, then you Unlike the exception (general dictionary & lt ;, & gt; ), the updated value will be found.

If you have not yet reached the modified item, you will eventually run through it; Otherwise, if you've already visited an updated item, you can remember the updated value.

From

The dictionary received from the dictionary is safe to use to read and write concurrently, though it's a moment-in-time snapshot of the dictionary Does not represent the content that comes through the calculator after the GetEnumerator can be amended in the dictionary.

For example, Thread 1 is running, now has 3 positions through the dictionary. If the modified element in the thread 2 position 7 will get the modified value, on the other hand, if this element is modified in 1 position, then you will not notice it. (Forget the fact that the dictionary is unarmed, used to better understand the situation).


I realized that your code is thinner through the code. Value (Thank you @ Noting in the comments for Swink); The above answer is true only if you loop through the dictionary, when you are walking through property again, you are actually looping through a snapshot. If the dictionary updates in the mean time, you will not notice it.


No comments:

Post a Comment