Passing async method into Parallel.ForEach

后端 未结 3 1295
无人及你
无人及你 2020-12-19 23:39

I was reading this post about Parallel.ForEach where it was stated that \"Parallel.ForEach is not compatible with passing in a async method.\"

So, to ch

3条回答
  •  悲&欢浪女
    2020-12-20 00:11

    An async method is one that starts and returns a Task.

    Your code here

    Parallel.ForEach(Enumerable.Range(0, 100), async index =>
    {
        var res = await DoAsyncJob(index);
        results.TryAdd(index.ToString(), res);
    });        
    

    runs async methods 100 times in parallel. That's to say it parallelises the task creation, not the whole task. By the time ForEach has returned, your tasks are running but they are not necessarily complete.

    You code works because DoAsyncJob() not actually asynchronous - your Task is completed upon return. Thread.Sleep() is a synchronous method. Task.Delay() is its asynchronous equivalent.

    Understand the difference between CPU-bound and I/O-bound operations. As others have already pointed out, parallelism (and Parallel.ForEach) is for CPU-bound operations and asynchronous programming is not appropriate.

提交回复
热议问题