我对如何做到这一点非常困惑。
我有一堆后台工作人员产生,所有人都需要使用Webclients downloadstringasync方法。
我的问题是如何从下载的字符串返回数据(一旦下载字符串完成事件发生),回到启动downloadstring的后台工作者?
我希望这是有道理的。任何建议将不胜感激。
答案 0 :(得分:0)
在工作线程中使用异步版本毫无意义。由于BackgroundWorker,代码已经异步运行。
所以只需使用DownloadString(),问题就解决了。
答案 1 :(得分:0)
如果使用WebClient.DownloadStringAsync
,它将在不同的线程上运行。您需要添加事件处理程序以在事件发生时收到通知。
例如:
此外,以下是一些从Google Async下载图片的示例代码。
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();
}
}
}