如何在不阻止UI的情况下使用WebClient? [英] How to use WebClient without blocking UI?

查看:113
本文介绍了如何在不阻止UI的情况下使用WebClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以指导我使用教程还是提供一些示例代码来调用System.Net.WebClient().DownloadString(url)方法,而无需等待结果时冻结UI?

Can someone point me to a tutorial or provide some sample code to call the System.Net.WebClient().DownloadString(url) method without freezing the UI while waiting for the result?

我认为这需要通过线程来完成?是否可以在没有太多开销代码的情况下使用一个简单的实现?

I assume this would need to be done with a thread? Is there a simple implementation I can use without too much overhead code?

谢谢!

已实现DownloadStringAsync,但UI仍处于冻结状态.有什么想法吗?

Implemented DownloadStringAsync, but UI is still freezing. Any ideas?

    public void remoteFetch()
    {
            WebClient client = new WebClient();

            // Specify that the DownloadStringCallback2 method gets called
            // when the download completes.
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(remoteFetchCallback);
            client.DownloadStringAsync(new Uri("http://www.google.com"));
    }

    public void remoteFetchCallback(Object sender, DownloadStringCompletedEventArgs e)
    {
        // If the request was not canceled and did not throw
        // an exception, display the resource.
        if (!e.Cancelled && e.Error == null)
        {
            string result = (string)e.Result;

            MessageBox.Show(result);

        }
    }

推荐答案

查看 WebClient.DownloadStringAsync()方法,这将使您异步发出请求,而不会阻塞UI线程.

Check out the WebClient.DownloadStringAsync() method, this'll let you make the request asynchronously without blocking the UI thread.

var wc = new WebClient();
wc.DownloadStringCompleted += (s, e) => Console.WriteLine(e.Result);
wc.DownloadStringAsync(new Uri("http://example.com/"));

(此外,完成操作后,别忘了Dispose()WebClient对象)

(Also, don't forget to Dispose() the WebClient object when you're finished)

这篇关于如何在不阻止UI的情况下使用WebClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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