DownloadStringAsync inside a Backgroundworker vb.net

本文关键字:vb net Backgroundworker inside DownloadStringAsync | 更新日期: 2023-09-27 18:35:06

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

我有一堆后台工作线程生成,它们都需要使用 Web 客户端下载字符串异步方法。

我的问题是如何将数据从下载的字符串(一旦下载字符串完成事件发生)返回给启动下载字符串的后台工作线程?

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

DownloadStringAsync inside a Backgroundworker vb.net

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

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

如果您使用 WebClient.DownloadStringAsync它会在不同的线程上运行。 您需要添加事件处理程序,以便在事件发生时收到通知。

例如:

  • WebClient.DownloadStringCompleted 事件

此外,这里有一些从谷歌异步下载图像的示例代码。

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();
        }

    }
}