Can i use async/await in class constructors?
I want my class constructor to send data to the database, so every instance of the class is synced with the corresponding item in the database. The problem is that database uses async, and i want to wait for the database to process the request, to output unique id, for me to use it later. Is there any way i can do that?
4 Replies
You can't put async/await in a constructor, no.
The most common way to get around this is to make the ctor private, and use a
public static async Task<YourClass> Create()
methodok, thanks, i will use Create method
if it's something you have to await it probably shouldn't be in a constructor anyway, constructors are meant for basic object initialization and should be very fast to run
The static factory method suggested by @Pobiega is the way to go. But there is an alternative. You can fire a Task from the constructor and then get the result using
await
later in a non-constructor method.