In my WPF Window_Loaded event handler, I have something like this:
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
// load data from database
this.Dispatcher.Invoke((Action)delegate
{
// update UI with loaded data
});
});
What I want to know is what happens when the user closes the form, when the data is loaded from the database and before this .Dispatcher.Invoke procedure starts?
Will an ObjectDisposedException be thrown? Or does the dispatcher ignore the Invoke routine (since the window is located)?
I tried to figure this out with some basic tests, but my results so far have been that nothing bad is happening. Exceptions are not thrown and the application does not crash.
And yet I had a few unpleasant events before when I used ThreadPool for the same. In the Window_Loaded event handler, I queued ThreadPool with a new user work item while the data was loading. I pressed the Esc key (I had a Window_KeyUp event handler for the Esc key, and if it was pressed, it was called this.Close ()), and the application crashed while trying to update the interface (inside Dispatcher.Invoke), since the window was already closed.
Since the task library uses ThreadPool behind the scenes, I'm afraid this could happen again if I don't write code to protect my application ...
- , , Dispatcher.Invoke?
, Invoke ? - ?
, ?
, , bool readyToClose = false; Window_Closing, , (! ReadyToClose) e.Cancel = true; , , readyToClose = true, , , .
try {...} catch (ObjectDisposedException) {// }?