1

我对如何做到这一点感到非常困惑。

我有一堆后台工作人员,他们都需要使用 Webclients downloadstringasync 方法。

我的问题是如何从下载的字符串中返回数据(一旦发生下载字符串完成事件),返回到启动下载字符串的后台工作人员?

我希望这是有道理的。任何建议,将不胜感激。

4

2 回答 2

0

在工作线程中使用异步版本完全没有意义。由于BackgroundWorker,代码已经异步运行。

所以只需使用 DownloadString() 代替,问题就解决了。

于 2013-10-12T02:42:43.740 回答
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();
        }


    }
}
于 2013-10-12T02:58:11.330 回答