I'm using ActionBlock
and I tested if it's working properly like below and sometime Actionblock
misses actions and it shouldn't happen at all
Why is this happening and how can i fix it?
var n = 0;
var action = new Action<int>((i) =>
{
n ;
//...job...
}
for (int i = 0; i < size; i )
{
var block = new ActionBlock<int>(i => action(i),
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 6 });
n = 0;
foreach (var a in list)
block.Post(a);
block.Complete();
block.Completion.Wait();
if (n != list.Count)
ShowError(); //it's called sometimes
}
CodePudding user response:
ActionBlock
can execute operations in parallel manner (and I believe it does exactly this in your case). So, in this case you just have a data race on n
operation.
So, actually the ActionBlock
does not miss anything, but you just calculating n
incorrectly and sometimes (may be almost all the time) get incorrect count at the end.
To get correct value of n
you may replace n
with Interlocked.Increment(ref n)
or just add a lock
.