1
我今天做了一個小測試,以更多地瞭解BackgroundWorker。BackgroundWorker不工作異步
在我看來,它不能在asychronuos模式下工作。首先它做了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();
}
}
}
您應該使用'Task.Run()'代替。 – SLaks
@GrantWinney:如果他有一個用戶界面,那會是真的。 – SLaks
@SLaks哈哈 - 哎呀。我會刪除我的評論。 –