简体   繁体   English

BackgroundWorker无法正常工作

[英]BackgroundWorker doesn't work Async

I made today small test to know more about BackgroundWorker. 我今天做了一个小测试,以了解有关BackgroundWorker的更多信息。

In my opinion it doesn't work in asychronuos mode. 我认为它在异步模式下不起作用。 First it did Do1 and next Do2. 首先执行Do1,然后执行Do2。 Do2 is shorter, Do1 takes more time, but program waits for Do1 finished and next start Do2. Do2较短,Do1需要更多时间,但是程序等待Do1完成并下次启动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 . 您将两个事件处理程序添加到同一BackgroundWorker
Like all other events, the DoWork event will run all of its handlers in order, synchronously. 与所有其他事件一样, DoWork事件将按顺序同步运行其所有处理程序。

To run two separate things asynchronously, you need two BackgroundWorker s. 要异步运行两个独立的事物,您需要两个BackgroundWorker

However, you should use Task.Run() instead; 但是,您应该改用Task.Run() it's much simpler & more composable. 它更简单,更容易组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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