Await ignored in c# asynchronous method

Question:

I need to use the return of an asynchronous method for validation but even with the use of "await" the method continues to be executed before I receive the return from 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;
}

Answer:

For asynchronous methods that return Task<object> in your Task<bool> , you have to access the "Result" property Example: Method

public static async Task<int> test()
    {
        Task t = Task.Factory.StartNew(() => {   Console.WriteLine("do stuff"); });
        await t;
        return 10;
    }

Call

static  void Main(string[] args)
{

    Task<int> test1 = Task.Factory.StartNew<int>(() => test());
    System.Console.WriteLine(test1.Result); // block and wait for the result
    Console.ReadLine();
}

https://stackoverflow.com/questions/25599074/how-do-you-get-the-return-value-of-an-async-method

What you can also do is define a callback method for your method.

private async void Search()
{
    await Search(SearchCompleted);//<--pass the callback method here
}

private async Task Search(Action<string> callback)
{
    //Here you're done with the file so invoke the callback that's it
    callback(file);//pass which file is finished 
}

private void SearchCompleted(string file)
{
    //this method will be called whenever a file is processed
}

https://stackoverflow.com/questions/19003594/fire-callback-after-async-task-method

Scroll to Top