【问题标题】:webClient.DownloadStringTaskAsync().Wait() freezes the UIwebClient.DownloadStringTaskAsync().Wait() 冻结 UI
【发布时间】:2011-10-17 02:05:22
【问题描述】:

我正在使用 silverlight 4 和新的异步 CTP。

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

此代码会导致 UI 冻结。
另一方面,这段代码运行良好:

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

这两者有什么区别,是什么导致第一个冻结?

【问题讨论】:

    标签: silverlight-4.0 task parallel-processing async-ctp


    【解决方案1】:

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

    第一个示例执行实际工作,即获取 www.google.com 并使用 .Wait() 将不允许事件处理程序在该页面下载之前返回。

    第二个例子只是调用Debug.WriteLine,即立即返回的调用,允许任务立即完成,所以你从未注意到.Wait()正在阻塞事件处理程序。

    您很可能希望使用.ContinueWith() 而不是.Wait() 来访问异步下载的结果。这样,事件处理程序会立即返回,您可以将代码放入 .ContinueWith() 块中以对下载的数据进行处理。

    【讨论】:

    • 但是第一个例子永远不会结束。它卡住了。为什么会这样?
    • 当我运行该代码时,它几乎立即返回。最好的办法是阻止请求连接的网络问题。代理指向错误的服务器,错误的 dns,不确定。
    猜你喜欢
    • 2019-01-27
    • 2022-01-25
    • 2015-01-16
    • 2019-09-16
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多