How do I call a method marked as async
in a class constructor?
How do I call a method marked as async
in a class constructor?
Constructors can not be marked as async
. There is a open discussion in the GitHub C # repository on the subject.
That said, there is no way to call a method and wait for it with the keyword await
.
An alternative is to create a static method that constructs the object. See in the example:
public static async Task<Foo> Construir() {
await MetodoAssincrono(); // chamada assíncrona
return new Foo(); // retorna instância do objeto construído
}
If you need to populate something inside the instance that comes from the return of this asynchronous method, do something like this:
public static async Task<Foo> Construir() {
var instancia = new Foo(); // constrói objeto
instancia.Dados = await GetDadosAsync(); // preenche o que precisa preencher; chamada assíncrona
return instancia; // retorna instância do objeto construído
}
Instead of
var obj = new Foo();
you would have
var obj = await Foo.Construir();
If you do not want a static method, create an asynchronous boot function within your class. After the object is built, call it:
var obj = new Foo();
await obj.Inicializar(); // Inicializar() retorna uma Task que será consumida aqui