C# 如何使用WebClient而不阻塞UI?
有人能给我指一个教程或提供一些示例代码来调用C# 如何使用WebClient而不阻塞UI?,c#,multithreading,webclient,downloadstring,C#,Multithreading,Webclient,Downloadstring,有人能给我指一个教程或提供一些示例代码来调用System.Net.WebClient().DownloadString(url)方法,而不必在等待结果时冻结UI吗 我想这需要一个线程来完成?是否有一个简单的实现,我可以使用没有太多的开销代码 谢谢 已实现DownloadStringAsync,但UI仍处于冻结状态。有什么想法吗 public void remoteFetch() { WebClient client = new WebClient();
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);
}
}
检查该方法,这将允许您在不阻塞UI线程的情况下异步发出请求
var wc = new WebClient();
wc.DownloadStringCompleted += (s, e) => Console.WriteLine(e.Result);
wc.DownloadStringAsync(new Uri("http://example.com/"));
(另外,完成后不要忘记处理()WebClient对象)您可以使用BackgroundWorker或@Fulstow所说的DownStringAsynch方法
这里有一个关于Backgorund worker的教程:Hmm。。。我实现了这个,但它仍然冻结了UI。这是我的代码:[贴在原来的帖子上面]