如何使用异步并等待耗时的方法 [英] how to use async and await on a method that is time comsuming

查看:102
本文介绍了如何使用异步并等待耗时的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的方法:

I have a method like this:

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

如您所见,它会阻塞UI线程.

As you can see, it blocks UI thread.

我可以创建一个backgroundWorker并在该后台线程上运行此方法,但是我想看看使用Async和Await是否可以帮助我简化此过程.

I can create a backgroundWorker and run this method on that background thread, but I am looking to see if using Async and Await would help me to simplify this.

这不起作用:

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

我该怎么做?

我想知道一般的解决方案,但也注意到MyimeConsumingTask正在等待网络上的一些数据,我该如何解决该问题?

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

推荐答案

要能够等待 MyTimeConsumingTask,必须声明它返回 Task .

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

public async Task<SimeType> MyTimeConsumingTask()

由于您说过要做一些网络IO,因此可以使用异步NW IO方法重写它,然后等待

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

但是在您的情况下,最简单的方法似乎是使用Task.Run

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.

这篇关于如何使用异步并等待耗时的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆