C# BackgroundWorker 和调用

C# BackgroundWorker and Invoke

有人可以解释为什么从 BackgroundWorker 调用 Thread.Sleep 会阻止它的执行。调用应导致委托在 UI 线程上执行,后台线程应继续执行。但这并没有发生 - 为什么?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        BackgroundWorker bgrw = new BackgroundWorker();
        bgrw.DoWork += new DoWorkEventHandler(bgrw_DoWork);

        bgrw.RunWorkerAsync();
    }

    void bgrw_DoWork(object sender, DoWorkEventArgs e)
    {
        Console.WriteLine(DateTime.Now);
        this.Invoke(new Action(() => { Thread.Sleep(2000); })); //should be executed on the UI thread
        Console.WriteLine(DateTime.Now); // This line is executed after 2 seconds
    }       
}

这是一个相当简单的解释。 Invoke 是一个 阻塞调用 。如果您想在 UI 消息循环上异步排队工作,请改用 BeginInvoke

Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on.

void bgrw_DoWork(object sender, DoWorkEventArgs e)
{
    Console.WriteLine(DateTime.Now);
    this.BeginInvoke(new Action(() => { Thread.Sleep(2000); })); 
    Console.WriteLine(DateTime.Now);
}  

请注意您的代码,因为当前构造没有意义。我假设您将其用于测试目的。