3
I need to use the return of an asynchronous method for validation but even with the use of "await" the method is still running before I receive the return of the function.
var teste = await new VendaService().EnviarVendaParaServicoCentral(new List<ItemVenda>(), new Venda());
if (teste)
{
MessageBox.Show("feito");
}
Asynchronous method with other asynchronous calls:
public async Task<bool> EnviarVendaParaServicoCentral(List<ItemVenda> itensVenda, Venda venda)
{
try
{
await this._conHelper._connection.Start();
this._vendaEfetuada = false;
await this._conHelper._hubProxy.Invoke("RealizarVenda", itensVenda, venda);
this._conHelper._hubProxy.On<bool>("RetornoDaVenda", (retornoServicoCentral) =>
this.Dispatcher.BeginInvoke(() =>
{
this._vendaEfetuada = retornoServicoCentral;
})
);
return this._vendaEfetuada;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return false;
}
@Jéfersonbueno that is the problem, I do not know what is wrong, he does not wait with the use of the await... the why is the doubt.
– Luiz Negrini
@Jéfersonbueno As far as I know, the await is used to force the wait.
– Luiz Negrini
Could you better explain the "method keeps running before I get the function return"? The variable value
teste
only exists after the function returns (actually, when its continuation is called, after the change that the compiler makes by await), then the continuation of the method (if (teste) ...
) is only executed after its function returns. Is not the case? If the lineif (teste)...
is running, so the variableteste
has a value, which was produced by the method that was awaited.– carlosfigueira
@That’s not the case.
– Luiz Negrini