简体   繁体   中英

Run background worker in parallel with Webclient file download

I have a background worker used for running a time consuming sync operation with server and is working perfectly and UI is responsive during the operation

        BackgroundWorker syncWorker = new BackgroundWorker();
        syncWorker.WorkerReportsProgress = true;            
        syncWorker.DoWork += new DoWorkEventHandler(syncWorker_DoWork);
        syncWorker.ProgressChanged += new ProgressChangedEventHandler(syncWorker_ProgressChanged);
        syncWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(syncWorker_RunWorkerCompleted);
    private void syncWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        foreach (xxxx item in actives)
        {
            target.ReportProgress(progress);
           //time taking event running fine here..
        }
        target.ReportProgress(90);          
    }
    private void syncWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
       lbl_progress.Text="Wait......";
    }

    private void syncWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
       lbl_progress.Text="DONE!..";
    }           

Now i have to do a file download operation and i am using Webclient to do it using the code

            WebClient  downloadClient = new WebClient();
            downloadClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadClient_DownloadProgressChanged);
            downloadClient.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadClient_DownloadFileCompleted);   
            downloadClient.DownloadFileAsync(new Uri(fileUrl), download_path);      
           void downloadClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
            {
                double bytesIn = double.Parse(e.BytesReceived.ToString());
                double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
                double percentage = bytesIn / totalBytes * 100;
                int progress_value = int.Parse(Math.Truncate(percentage).ToString());
                progress_value = (progress_value < 5) ? 5 : (progress_value > 95) ? 95 : progress_value;          
                lblDownloadProgress.Content = string.Format("DOWNLOADING - {0}%", progress_value.ToString());
            }
            void downloadClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
            {
                string item = (string)e.UserState;
                if (e.Error != null )
                {

                    lblDownloadProgress.Content = "Unable to download.Try again.....";
                    lblDownloadProgress.Foreground = Brushes.Red;
                }
                else if (e.Cancelled)
                {
                    //Do Nothing
                }
                else
                {
                    lblDownloadProgress.Content ="DOWNLOADED..";
                }
            }

Now can i run these 2 things parallely ? Like run background worker while downlaoding the file?? if file downloading finished first wait till the completion of background worker if background worker finished first wait till completion of download
Enable controls after both operations finished and keep UI responsive during the whole time

You can run 2 Background worker in parallel but if you need check the state of one of them you can check if the backgroundworker is busy(doing work or completed).

private void syncWorker_DoWork(object sender, DoWorkEventArgs e)
    {
     while( downloadClient.IsBusy)
            {

             Sleep(5000);

             //waiting downloadClient  worker to complete
            }

             //continue the work
}

look into this for check some trick you can do.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Threading;

namespace download_demo
{
    class Program
    {


        static void Main(string[] args)
        {   
            BackgroundWorker MyWorker = new BackgroundWorker();
           MyWorker.DoWork += MyWorker_DoWork;
           MyWorker.RunWorkerCompleted +=MyWorker_RunWorkerCompleted;
           MyWorker.RunWorkerAsync();
           Console.ReadKey();
        }

        private static void MyWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Console.WriteLine("both job completed");
        }

        private static void MyWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Thread download = new Thread(DownloadJob);
            download.Start();
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(20);
                Console.WriteLine("doing some job while downloading ");

            }
            Console.WriteLine("waiting the end of download......... ");
            download.Join();

        }

        private static void DownloadJob(object path)
        {
           /// process download the path
           ///simulate 20 seconde of download
           for(int i = 0;i<100;i++)
           {
               Thread.Sleep(50);
               Console.WriteLine("downloaded :" + i + " Ko");
           }
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM