webClient.DownloadStringTaskAsync().Wait() freezes the UI

人盡茶涼 提交于 2019-12-08 13:03:54

问题


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

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 ?


回答1:


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

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.

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.

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.



来源:https://stackoverflow.com/questions/6892689/webclient-downloadstringtaskasync-wait-freezes-the-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!