Does LINQ AsParallel() preserve thread safety?

与世无争的帅哥 提交于 2020-06-28 03:15:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!