2
How do I call a method marked as async
in a class builder?
2
How do I call a method marked as async
in a class builder?
3
Manufacturers shall not be marked as async
. There is a open discussion in the C# language repository on Github 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 builds 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 fill in something within 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 built object, call:
var obj = new Foo();
await obj.Inicializar(); // Inicializar() retorna uma Task que será consumida aqui
If it wasn’t possible I knew because builders can’t be async. I saw something on Soen and I’m looking and I’m not finding it. A guy did something, he solved a problem similar to mine, but as I was, that day looking for something else and I saw and now I do not know the address of that solution, but I will think of something like your solution. I’ll see what I can do.
I don’t remember exactly how it was, but it might be something you posted
Browser other questions tagged c# asynchronous builder
You are not signed in. Login or sign up in order to post.
Yes, it is loaded on an Android App and I need it to be asynchronous.
– pnet
What does this method do? Fills something of the instance?
– vinibrsl
@vnbrs, the method brings me the information that a given service provides. I will use them to fill a Chart
– pnet