[Solved] how to use async and await on a method that is time comsuming [closed]


To be able to await MyTimeConsumingTask it must be declared to return a Task.

public async Task<SimeType> MyTimeConsumingTask()

Since you said it does some network IO, you can rewrite it using async NW IO methods and then await it as

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)); 

Comparing 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 definitely prefer the first one, but the 2nd one is easier to use if it is already working and hard to change method.

solved how to use async and await on a method that is time comsuming [closed]