问题
I'm having some doublts about concurrency using LINQ
AsParallel()
.
Suppose I have the following code:
int counter = 0;
someList.AsParallel().ForEach(item => {
doStuff();
counter++;
});
I haven't found much online...
Is it safe to do something like this? Is there a better way of doing this?
Should I do some locking action for counter
?
Thanks in advance
回答1:
Is it safe to do something like this? (
counter++
)
No.
There is no thread-safety to begin with, just code that is single-threaded.
When going parallel, you should make sure everything is thread-safe.
In this case:
//counter++;
Interlocked.Increment(ref counter);
And we can't see what DoStuff()
is doing. All invocations should be independent (or use a form of locking).
来源:https://stackoverflow.com/questions/51080492/does-linq-asparallel-preserve-thread-safety