Reputation: 1823
Initial Info:
I have a method that gets data from a database and splits it up into logical parts (for sake of simplicity, let's just say that this number is always 8 unequal parts). For each part, I start a new background thread to write data up to the database.
In doing this, I will end up with 8 asynchronous threads running, all using the same _DoWork() and _RunWorkerCompleted() methods.
When a thread is started, it will immediately be added a list of background workers. In the _RunWorkerCompleted() method, I remove that background worker from the list and check if the list of background workers has a count of 0; if not I continue, if so, then I must let the user know that the operation has completed.
The problem:
Before any of the threads start, I call Mouse.OverrideCursor = Cursors.Wait; in order to show a waiting cursor. When everything completes, I must call Mouse.OverrideCursor = null; in order to force the mouse cursor to go back to it's normal state.
However, when I call this in the _RunWorkerCompleted() method inside the if statement asking if the bw list has a count of 0, I get a run-time exception stating that another thread owns that object.
How do I call Mouse.OverrideCursor = null; after all threads complete without a run-time exception?
Note:
I've also been having this same problem with trying to display a MessageBox from inside the _RunWorkerCompleted() method. I thought _RunWorkerCompleted() was on the UI thread?
Any help will be greatly appreciated.
P.S., if any code is needed to better assess the problem, please ask and be specific as to which part of the code you would like to see (there's a quite bit going on behind these methods, I don't want to confuse anyone by posting too much code).
Regards,
Kyle
Upvotes: 0
Views: 578
Reputation: 3429
When you call RunWorkerCompleted method if you need to update the UI you have to use the Dispatcher like this in order to update it in the UI thread :
this.Dispatcher.Invoke(() =>
{
// YOUR UI UPDATE
});
Upvotes: 1