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?
I’m using BackgroundWorker for the first time, and use is not entirely clear. Can
Share
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 usingInvoke()orBeginInvoke()for UI interaction, or proper thread synchronization for other cross-thread operations), which would defeat the purpose of theBackgroundWorker.The better option is to call
ReportProgress(), which then raises theProgressChangedevent in a thread-safe manner. You pass anintrepresenting the percentage complete (though it’s up to you to actually do something with it) and, optionally, anyobjectthat 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.