When trying to set the main method in the console application to asynchronous, an error may be encountered: "The Main method that cannot specify the 'async' modifier in the main method of the console application".
The compiler limits
Historically, the Visual Studio compiler limits the use of Async modifier on the main method. This is to prevent the asynchronous implementation of the natural synchronization behavior of the console program.
The support of the asynchronous Main
However, starting with Visual Studio 2017 Update 3 (15.3), C# supports the asynchronous main method, as long as they return Task or Task . This allows the following code structure:
Understanding behavior
1 2 3 4 5 6 7 |
|
Avoid the procedure from exiting
In order to prevent the procedure from exiting, it is necessary to provide a context compatible with asynchronous compatibility for the main method. This context maintains the program in a state of activity during the operation of asynchronous operation.
The context option
Nuget library:
use the asynccontext in Nito.asyncex Nuget bag.asynchronous CTP: GoneralthReadaffineContext in the asynchronous CTP (if available).
The above is the detailed content of Can I Make My Console Application's Main Method Asynchronous?. For more information, please follow other related articles on the PHP Chinese website!