简体   繁体   中英

BackgroundWorker doesn't work Async

I made today small test to know more about BackgroundWorker.

In my opinion it doesn't work in asychronuos mode. First it did Do1 and next Do2. Do2 is shorter, Do1 takes more time, but program waits for Do1 finished and next start Do2. Am I right? Thank you!

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

namespace ConsoleApplication16
{
    public interface I 
   {
        void UstawWiek(string w);
        void PokazWiek(); 
   }

    class rrr
    {

        public delegate void MojDelegat();

        public static void Do1(object sender, DoWorkEventArgs e)
        {
            System.Threading.Thread.Sleep(4000);
            Console.WriteLine("Do1");
        }

        public static void Do2(object sender, DoWorkEventArgs e)
        {
            System.Threading.Thread.Sleep(1000);
            Console.WriteLine("Do2");
        }


        static void Main(string[] args)
        {          

           BackgroundWorker bw = new BackgroundWorker();
           bw.DoWork += new DoWorkEventHandler(Do1);
           bw.DoWork += new DoWorkEventHandler(Do2);
           bw.RunWorkerAsync();

           int i =0;
           while ( bw.IsBusy)
           {
           Console.WriteLine("Waiting {0}",i);
           System.Threading.Thread.Sleep(100);
           i++;
           }

           Console.WriteLine("Done!"); 
           Console.ReadKey();

        }
    }     
}

You added two event handlers to the same BackgroundWorker .
Like all other events, the DoWork event will run all of its handlers in order, synchronously.

To run two separate things asynchronously, you need two BackgroundWorker s.

However, you should use Task.Run() instead; it's much simpler & more composable.

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