C# constructor can the constructor use Async keywords?
In C#, the constructor is the entrance point of the initialized instance. Different from ordinary methods, the constructor cannot use Async modifier. This restriction comes from the inherent architectural constraint.
The reason behind the limit:
When using ASYNC keywords in the constructor, the compiler generates an asynchronous state machine. This state machine needs to access the instance that is being constructed, but this instance is not available before the constructor is executed. This asynchronous state machine also needs to be saved and restored as part of the life cycle of the object, including during the period of serialization and desertification. Treatment of this complexity will bring huge expenses and potential object management issues.
Changing Plan:
Although the async cannot be used directly in the constructor, there are some alternative strategies:
Static asynchronous method:
Create a static asynchronous method for returning the class instance. Initize instances in a private structure function called by the asynchronous method. (As shown in the code provided by the "Question Answer" part)Internal method:
The above is the detailed content of Can C# Constructors Be Asynchronous (Async)?. For more information, please follow other related articles on the PHP Chinese website!