C# 在Backgroundworker vb.net中下载StringAsync
我很困惑如何做到这一点 我有一群后台工作人员,他们都需要使用WebClient downloadstringasync方法 我的问题是如何将下载字符串中的数据(一旦下载字符串完成事件发生)返回给启动下载字符串的后台工作程序C# 在Backgroundworker vb.net中下载StringAsync,c#,vb.net,asynchronous,backgroundworker,webclient,C#,Vb.net,Asynchronous,Backgroundworker,Webclient,我很困惑如何做到这一点 我有一群后台工作人员,他们都需要使用WebClient downloadstringasync方法 我的问题是如何将下载字符串中的数据(一旦下载字符串完成事件发生)返回给启动下载字符串的后台工作程序 我希望这是有道理的。任何建议都将不胜感激。在工作线程中使用异步版本毫无意义。由于BackgroundWorker,代码已经异步运行 所以只需使用DownloadString(),问题就解决了。如果您使用的是WebClient.DownloadStringAsync它运行在不同
我希望这是有道理的。任何建议都将不胜感激。在工作线程中使用异步版本毫无意义。由于BackgroundWorker,代码已经异步运行
所以只需使用DownloadString(),问题就解决了。如果您使用的是
WebClient.DownloadStringAsync
它运行在不同的线程上。您需要添加事件处理程序,以便在事件发生时获得通知
例如:
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
namespace WebDownload
{
class Program
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static void Main(string[] args)
{
WebClient client = new WebClient();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
string fileName = Path.GetTempFileName();
client.DownloadFileAsync(new Uri("https://www.google.com/images/srpr/logo11w.png"), fileName, fileName);
// Wait for work method to signal.
if (autoEvent.WaitOne(20000))
Console.WriteLine("Image download completed.");
else
{
Console.WriteLine("Timed out waiting for image to download.");
client.CancelAsync();
}
}
private static void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
Console.WriteLine(e.Error.Message);
if (e.Error.InnerException != null)
Console.WriteLine(e.Error.InnerException.Message);
}
else
{
// We have a file - do something with it
WebClient client = (WebClient)sender;
// display the response header so we can learn
Console.WriteLine("Response Header...");
foreach(string k in client.ResponseHeaders.AllKeys)
Console.WriteLine(" {0}: {1}", k, client.ResponseHeaders[k]);
Console.WriteLine(string.Empty);
// since we know it's a png, let rename it
FileInfo temp = new FileInfo((string)e.UserState);
string pngFileName = Path.Combine(Path.GetTempPath(), "DesktopPhoto.png");
if (File.Exists(pngFileName))
File.Delete(pngFileName);
File.Move((string)e.UserState, pngFileName); // move to where ever you want
Process.Start(pngFileName); // display the photo for the fun of it
}
// Signal that work is finished.
autoEvent.Set();
}
}
}
我这样做的原因是,我可以使用cancelasync使其超时,因为我使用的代理喜欢导致正常下载字符串挂起。-1 asych和concurrent是稍微不同的事情。使用后台工作线程会消耗线程。异步回调不使用线程。在x64机器上,线程使用8mb内存。以及其他资源。@HansPassant,这是真的。但是您说过在工作线程中使用异步版本没有意义。使用线程池线程不会降低线程的成本。一根线仍在使用。如果有1000个请求,在后台线程中使用Synchronous
DownloadString()
会在线程池最大化时阻塞,或者会在线程池上创建新线程。至于在DownloadStringAsync()
中使用后台工作线程,它将请求创建转移到工作线程上,这在UI密集型应用程序中可能很重要。他已经在使用BGW了。他可以用它做两件事,调用DownloadString()或阻止它,直到DownloadStringAsync完成。这些选择中只有一个是有意义的。