I'm using BackgroundWorker for the first time, and use is not entirely clear. Can I send events directly from the DoWork handler, or do I have to instead call ReportEvents and send the event from the ProgressChanged handler?
While it's technically possible to raise events and work with the UI from within DoWork
, you would have to do so just as you would from within any other thread (by using Invoke()
or BeginInvoke()
for UI interaction, or proper thread synchronization for other cross-thread operations), which would defeat the purpose of the BackgroundWorker
.
The better option is to call ReportProgress()
, which then raises the ProgressChanged
event in a thread-safe manner. You pass an int
representing the percentage complete (though it's up to you to actually do something with it) and, optionally, any object
that you would require to obtain specific information about the event or the progress. From within ProgressChanged you can interact with the UI, raise events, etc.