【问题标题】:How to use WebClient without blocking UI?如何在不阻塞 UI 的情况下使用 WebClient?
【发布时间】:2011-09-01 09:44:27
【问题描述】:

谁能指点我一个教程或提供一些示例代码来调用System.Net.WebClient().DownloadString(url) 方法而不会在等待结果时冻结 UI?

我认为这需要使用线程来完成?有没有我可以使用而无需太多开销代码的简单实现?

谢谢!


实现了 DownloadStringAsync,但 UI 仍然冻结。有什么想法吗?

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

        }
    }

【问题讨论】:

    标签: c# multithreading webclient downloadstring


    【解决方案1】:

    查看WebClient.DownloadStringAsync() 方法,这将让您在不阻塞 UI 线程的情况下异步发出请求。

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

    (另外,完成后不要忘记 Dispose() WebClient 对象)

    【讨论】:

    • 嗯...我实现了这个,它仍然冻结了 UI。这是我的代码:[粘贴在上面的原始帖子中]
    【解决方案2】:

    您可以使用 BackgroundWorker 或 @Fulstow 所说的 DownStringAsynch 方法。

    这是关于 Backgorund worker 的教程:http://www.dotnetperls.com/backgroundworker

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      相关资源
      最近更新 更多