后台工作线程不工作异步



我今天做了一个小测试,以了解更多关于BackgroundWorker的信息。

在我看来,它在时空模式下不起作用。首先它做了Do1,接下来做了Do2。Do2 更短,Do1 需要更多时间,但程序等待 Do1 完成并启动 Do2。我说的对吗?谢谢!

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

您向同一BackgroundWorker添加了两个事件处理程序。
与所有其他事件一样,DoWork 事件将按顺序同步运行其所有处理程序。

要异步运行两个单独的内容,您需要两个BackgroundWorker

但是,你应该改用Task.Run();它更简单,更易于组合。

最新更新