How to use WebClient without blocking UI?

不问归期 提交于 2019-12-10 13:59:39

问题


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?

Thanks!


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

        }
    }

回答1:


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

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




回答2:


You could use a BackgroundWorker or as @Fulstow said the DownStringAsynch method.

Here's a tutorial on Backgorund worker: http://www.dotnetperls.com/backgroundworker



来源:https://stackoverflow.com/questions/6118796/how-to-use-webclient-without-blocking-ui

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