Should Task.Wait be deprecated?

I have learned that calling Task.Wait from a thread in a pool can lead to a deadlock in the thread.

In accordance with this MSDN article in the "Dead Ends" chapter, we must abide by these two rules:

  • Do not create a class whose synchronous methods are waiting for asynchronous functions, since this class can be called from a thread in the pool.
  • Do not use any class inside an asynchronous function if the class blocks expectations of asynchronous functions.

It seems the only place left for the legitimate use of Task.Wait is the main function - I exaggerate a bit here, but you get the idea.

Why is Task.Wait still part of the .NET platform, seeing how dangerous it is?

+5
source share
1 answer

Why is Task.Wait still part of the .NET platform, seeing how dangerous this is?

Because you want to be able to synchronously block on Task . Rarely, but you still do. As you said, Main is probably the most popular (and preferably the only) place where this will happen. It is also a fact that Microsoft is notorious for its backward compatibility, so once it has been introduced, it is unlikely that it will be obsolete or disappear from BCL. The same goes for Task.WaitAll .

The real problem of IMO begins when people do not read the documentation well and do not understand the consequences of calling this method and ultimately abuse it. If you use it carefully, it works great.


Another thing is that you cannot always go asynchronously. Unfortunately, many times you have code that is synchronous in signature, which cannot be changed and needs to call an asynchronous call method. Yes, it is dangerous and discouraged by everyone, and is considered an anti-pattern with asynchronous code , and I myself answered at least a dozen questions about SO, where people end up getting stuck and don’t understand why, but TPL authors still needed to make these types of calls possible.

+5
source

Source: https://habr.com/ru/post/1234540/


All Articles