How to use async and wait in a method that is comsuming time

I have a way like this:

public void ButtonClicked()
{
     var MyResult=MyTimeConsumingTask(MyClassProperty); 
 }

      

As you can see, it blocks the UI thread.

I can create a backgroundWorker and run this method on that background thread, but I want to see if using Async and Await helps me to make it easier.

This does not work:

public async void ButtonClicked()
{
    await var MyResult=MyTimeConsumingTask(MyClassProperty); 
}

      

How can i do this?

I like to know the general solution, but also noting that MyimeConsumingTask is waiting for some data on the network, how can I solve the problem?

-3


source to share


1 answer


To be able to wait MyTimeConsumingTask

, it must be declared to return a Task.

public async Task<SimeType> MyTimeConsumingTask()

      

Since you said it does some network I / O, you can rewrite it with NW IO async methods and then wait for it like

var MyResult = await MyTimeConsumingTask(MyClassProperty);

      

But in your case, the simplest approach seems to be using Task.Run

var MyResult = await Task.Run(() => MyTimeConsumingTask(MyClassProperty)); 

      




Comparison of these two approaches:

1.

public async Task<string> GetHtmlAsync(string url)
{
    using (var wc = new Webclient())
    {
        var html = await wc.DownloadStringTaskAsync(url);
        //do some dummy work and return
        return html.Substring(1, 20);
    }
}

var str1 = await GetHtmlAsync("http://www.google.com");

      

2.

public string GetHtml(string url)
{
    using (var wc = new Webclient())
    {
        var html = wc.DownloadString(url);
        //do some dummy work and return
        return html.Substring(1, 20);
    }
}

var str2 = await Task.Run(()=>GetHtml("http://www.google.com"));

      

I would prefer the first option, but the second is easier to use if it already works and it is difficult to change the method.

+3


source







All Articles