1

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
    }       
}
Yuval Itzchakov
  • 136,303
  • 28
  • 230
  • 296
  • 2
    "Invoke should cause the delegate to be executed on the UI thread" - yes - "and background thread should continue" - no. Look at the definition for [`Invoke`](https://msdn.microsoft.com/en-us/library/zyzhdc6b(v=vs.110).aspx) and note that it's return value is whatever the delegate returned. It can't return that value to you until the code has completed executing. `Invoke` blocks. – Damien_The_Unbeliever Feb 17 '15 at 08:31
  • Why not just call Thread.Sleep() from the UI Thread right after you started your Backgroundworker ? – Paul Weiland Feb 17 '15 at 08:34
  • Read this http://stackoverflow.com/a/229558/4112271 – Amol Bavannavar Feb 17 '15 at 08:35

1 Answers1

7

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.

Yuval Itzchakov
  • 136,303
  • 28
  • 230
  • 296