-->

How to use WebClient without blocking UI?

2019-06-21 04:53发布

问题:

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