如何使用WebClient而不阻塞UI?
有人可以向我指出教程或提供一些示例代码来调用 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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 WebClient.DownloadStringAsync() 方法,这可以让您异步发出请求而不阻塞 UI 线程。
(另外,完成后不要忘记 Dispose() WebClient 对象)
Check out the WebClient.DownloadStringAsync() method, this'll let you make the request asynchronously without blocking the UI thread.
(Also, don't forget to Dispose() the WebClient object when you're finished)
您可以使用BackgroundWorker 或@Fulstow 所说的DownStringAsynch 方法。
这是有关 Backgorund Worker 的教程:http://www.dotnetperls.com/backgroundworker
You could use a BackgroundWorker or as @Fulstow said the DownStringAsynch method.
Here's a tutorial on Backgorund worker: http://www.dotnetperls.com/backgroundworker