DownloadStringAsync()不会异步下载字符串

本文关键字:异步 下载 字符串 DownloadStringAsync | 更新日期: 2023-09-27 17:57:40

在下载一字节数据时,尝试实现downloadStringAsync()以防止UI冻结10秒。然而,即使下载完成,它也会冻结UI,就像我使用downloadString()一样。

这是我的代码:

    public void loadHTML()
    {
            WebClient client = new WebClient();
            // Specify that the DownloadStringCallback2 method gets called
            // when the download completes.
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(loadHTMLCallback);
            client.DownloadStringAsync(new Uri("http://www.example.com"));
            return;
    }
    public void loadHTMLCallback(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;
            // Do cool stuff with result
        }
    }

DownloadStringAsync()不会异步下载字符串

遇到了同样的问题,并找到了解决方案。这里的讨论相当复杂:http://social.msdn.microsoft.com/Forums/en-US/a00dba00-5432-450b-9904-9d343c11888d/webclient-downloadstringasync-freeze-my-ui?forum=ncl

简而言之,问题是web客户端正在搜索代理服务器并挂起应用程序。以下解决方案有帮助:

WebClient webClient = new WebClient();
webClient.Proxy = null;
... Do whatever else ...