Reputation: 1045
Im reading a WPF book and I see this code:
private void bgw1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int percenti;
percenti = e.ProgressPercentage;
progressBar1.Value = percenti;
}
The question is simple. if
ProgressBar belongs to UI Thread and BackGroundWorker works with a Background Thread
Why are there no errors (like: The calling thread cannot access this object because a different thread owns it.)?
thanks.
Upvotes: 1
Views: 1543
Reputation: 41
It is because you cannot make changes in the Do_work method of the background worker. progress_changed event keeps updating what is happening in the other thread.
Bes to clear your concept through this link--> [https://www.codeproject.com/Articles/99143/BackgroundWorker-Class-Sample-for-Beginners][1]
Upvotes: 0
Reputation: 49659
The BackgroundWorker
handles the thread context switch for you. The event BackgroundWorker.ProgressChanged
will be raised on the UI-Thread and hence your callback bgw1_ProgressChanged
will be called in the context of the UI-Thread.
This was the main purpose for the BackgroundWorker
's existence: To make async work easy and straight forward in conjunction with a UI.
BackgroundWorker
exists since .NET 1.0. Now that we live in 2012, we have the Task class and the Task Parallel Library and soon the c# async
keyword as general means for everything async, wich makes the BackgroundWorker
kind of obsolete or at least old school.
Upvotes: 2
Reputation: 564931
Why are there no errors (like: The calling thread cannot access this object because a different thread owns it.)?
This is one of the main advantages to using BackgroundWorker
. The BackgroundWorker component automatically marshals calls for progress and completion back to the synchronization context (thread) that starts the job.
In this case, that means that the event handlers for ProgressChanged
(and the completion event) happen on the WPF UI thread.
Upvotes: 3