Await ignored in asynchronous method c #

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 get the function return.

    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;
}
    
asked by anonymous 22.09.2015 / 19:15

1 answer

1

For asynchronous methods that return Task<object> in your Task<bool> case, you have to access the property "Result" 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();
}

p>

What you can do is also define a call back 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
}

link

    
30.09.2015 / 18:29