简体   繁体   中英

C# BackgroundWorker and Invoke

Can someone explain why invoking Thread.Sleep from BackgroundWorker blocks its execution. Invoke should cause the delegate to be executed on the UI thread and background thread should continue with execution. But that does not happen - why?

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
    }       
}

It's a rather simple explanation. Invoke is a blocking call . If you want to queue work on the UI message loop asynchronously, use BeginInvoke instead:

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

Note your code, as currently constructed makes no sense. I'm assuming you're using this for testing purposes.

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