AsParallel.ForAll vs Parallel.ForEach

前端 未结 4 1147
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 15:11

Is there any difference between the below code snippets. If so, what?

myList.AsParallel().ForAll(i => { /*DO SOMETHING*/ });

and

Pa

4条回答
  •  情歌与酒
    2021-01-31 15:53

    Here is an explanation in MSDN:

    https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/potential-pitfalls-with-plinq#prefer-forall-to-foreach-when-it-is-possible

    Based on what I read, use Parallel.ForEach() if you want to ensure the list are access sequentially while using AsParallel.ForAll() does not guarantee the items in the list are accessed in order.

    For MVC, all thread are request-based. The caller thread (main) is blocked until the Parallel() call is completed, that means all child threads should have completed as well.

    If the caller thread is aborting, here is an explain:

    http://www.albahari.com/threading/part5.aspx

    PLINQ doesn't preemptively abort threads, because of the danger of doing so. Instead, upon cancellation it waits for each worker thread to finish with its current element before ending the query. This means that any external methods that the query calls will run to completion.

提交回复
热议问题