webClient.DownloadStringTaskAsync()。等待()将冻结UI [英] webClient.DownloadStringTaskAsync().Wait() freezes the UI

查看:147
本文介绍了webClient.DownloadStringTaskAsync()。等待()将冻结UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Silverlight 4中,和新的异步CTP。

I am using silverlight 4, and the new async CTP.

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            WebClient wb = new WebClient();
            var t = wb.DownloadStringTaskAsync("http://www.google.com");
            t.Wait();            
        }

这code使UI冻结。结果
在另一方面,这code正常工作:

This code causes the UI to freeze.
On the other hand, this code works fine :

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            WebClient wb = new WebClient();
            var t = Task.Factory.StartNew(() => Debug.WriteLine("Doing something"));
            t.Wait();            
        }

请告诉我两个,什么之间的差导致第一个冷冻

Whats the difference between the two, and what causes the first one to freeze ?

推荐答案

.Wait()的任务阻塞,直到它完成。

.Wait() blocks on the Task until it has completed.

第一个例子做实际的工作,即取的 www.google.com 的并用 .Wait()将不允许事件处理程序返回到该页面已经被下载。

The first example does actual work, i.e. fetches www.google.com and with .Wait() will not allow the event handler to return until that page has been downloaded.

第二个例子只调用的Debug.WriteLine ,即可以立即返回,使任务立即完成,所以你从来没有注意到一个呼叫 .Wait()挡住了事件处理程序。

The second example merely calls Debug.WriteLine, i.e. a call that returns immediately, allowing the Task to complete immediately, so you never noticed that .Wait() is blocking the event handler.

最有可能你需要使用 .ContinueWith()而不是 .Wait()来访问从异步下载结果。这样的事件处理程序立即返回,而你可以把code在 .ContinueWith()块做数据下载的东西。

Most likely you'll want to use .ContinueWith() instead of .Wait() to access the result from the async download. That way the event handler immediately returns and you can put code in the .ContinueWith() block to do something with the data downloaded.

这篇关于webClient.DownloadStringTaskAsync()。等待()将冻结UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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