Home > database >  Using Task.Wait on a parallel task vs asynchronous task
Using Task.Wait on a parallel task vs asynchronous task

Time:01-17

In chapter 4.4 Dynamic Parallelism, in Stephen Cleary's book Concurrency in C# Cookbook, it says the following:

Parallel tasks may use blocking members, such as Task.Wait, Task.Result, Task.WaitAll, and Task.WaitAny. In contrast, asynchronous tasks should avoid blocking members, and prefer await, Task.WhenAll, and Task.WhenAny.

I was always told that Task.Wait etc are bad because they block the current thread, and that it's much better to use await instead, so that the calling thread is not blocked.

Why is it ok to use Task.Wait etc for a parallel (which I think means CPU bound) Task?

CodePudding user response:

One of the risks of Task.Wait is deadlocks. If you call .Wait on the UI thread, you will deadlock if the task needs the main thread to complete. If you call an async method on the UI thread such deadlocks are very likely.

If you are 100% sure the task is running on a background thread, is guaranteed to complete no matter what, and that this will never change, it is fine to wait on it.

Since this if fairly difficult to guarantee it is usually a good idea to try to avoid waiting on tasks at all.

CodePudding user response:

I believe that point in this passage is to not use blocking operations like Task.Wait in asynchronous code.

The main point isn't that Task.Wait is preferred in parallel code; it just says that you can get away with it, while in asynchronous code it can have a really serious effect.

This is because the success of async code depends on the tasks 'letting go' (with await) so that the thread(s) can do other work. In explicitly parallel code a blocking Wait may be OK because the other streams of work will continue going because they have a dedicated thread(s).

  • Related