-1

Suppose, I make a BackgroundWorker like this

private void RunBackgroundWorker(object sender, DoWorkEventArgs e)
{
    //  Do something lengthy here
    // which takes a lot of time
}
private void BackgroundWorkerCompleted(object sender, RunWorkerCompletedEventArgs)
{
     System.Threading.Thread.Sleep(2000) ; 
     BackgroundWorker1.RunWorkerAsync() ; 
}

I want to ask whether the contents of BackgroundWorkerCompleted function are executed on the "Background" thread or the main UI thread. I am asking this because, I am creating a desktop, app which uses the database and constantly updates it's database after every few seconds

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Pratik Singhal
  • 6,283
  • 10
  • 55
  • 97

2 Answers2

2

It executes on the UI thread. MSDN explains:

You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the ProgressChanged and RunWorkerCompleted events.

That said, Servy was correct in the comments -- you should be using a Timer for executing code on an interval, not a BackgroundWorker.

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
  • If there is a lengthy process then it should be put in a BackgroundWorker to prevent freezing the UI. – Rick Hodder Nov 27 '13 at 22:02
  • @RickHodder The `RunWorkerCompleted` event isn't for long-running processes --it's for updating the UI with the *result* of a long-running process. – Daniel Mann Nov 28 '13 at 00:38
1

I am using BackgroundWorker a lot and can tell that RunWorkerCompleted event is definitely ran in UI thread. Also, you can pass the DoWork result to according eventArgs field and then, in RunWorkerCompleted take it from eventArgs to perform some UI-dependent operations with it, as mentioned here

Community
  • 1
  • 1