SOLVED - PLEASE SEE COMMENTS BELOW IF YOU ARE INTERESTED IN HOW THIS WORKED OUT, SINCE IT IS A 2-PART SOLUTION, BOTH OF WHICH ARE POTENTIALLY USEFUL TO OTHERS.
Often, users will go to my program's "import data" window to initiate an import of data from a file or spreadsheet to our database. Depending on the size of the import, though, this can take up to 2 minutes.
Therefore, to reduce this time, I have decided to get a head start on the predictable aspects of the import process during program initialization, by using a
As the data import progresses, the data import classes are busy raising the
BackgroundWorker.ReportProgress event, passing in a state object in the
ProgressChangedEventArgs. The state object has all the data to show a
ProgressBarand some other state like number imported, an icon, popup message, etc., but there is no UI (yet) to display this progress.
But then if the user is quick enough, they can get to the "import data" window before the background import is done. It is still in progress in the
So when that window loads, I "tune in" to the state of the import process, by handling the
ProgressChangedevent of the BackgroundWorker. This keeps the user amused while the process completes.
By the way: Since this is a Windows Forms application, I can tell you that I have had lots of trial-and-error fun with cross-thread errors trying to update UI controls from the BackgroundWorker thread. I finally gave up on all that and decided to try and use the
Back to the sad story: However, at this point, the user may now decide to re-import, or change some properties that were preventing the success of the import, and proceed to initiate the import "manually", as they used to do before I implemented this
So now the program is doing another data import, and of course I want to use the same classes that the
BackgroundWorkerused, but this time, it's going to be done in the UI thread.
BackgroundWorker.ReportProgress event that my import classes were raising to the
BackgroundWorkerneed to be handled instead by the UI thread.
I have this foggy notion that a
Delegatecould be used to report progress to either the UI thread or the
BackgroundWorkerthread, but I don't have a lot of experience with using them.
So here's my question: How can I use a
Delegateto send this progress to the
BackgroundWorkerif it's running, but to the UI if the process is initiated there?
Or, do I need a to abandon the BackgroundWorker idea and teach myself how to use something like the more complicated
Event-based Asynchronous Patternas explained in the MSDN article entitled "Event-based Asynchronous Pattern Overview"?