开发者

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

开发者 https://www.devze.com 2023-03-23 23:23 出处:网络
I开发者_开发技巧 am using silverlight 4, and the new async CTP. private void button1_Click(object sender, RoutedEventArgs e)

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 ?


.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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号