Reputation: 151
I'm using async tasks to upload files and update the database. I need to know when the application is closed to update the upload status in the DB.
My task is in a ViewModel class.
private async void OnUpload(object param)
{
await Task.Factory.StartNew(() =>
{
try
{
...
}
catch (Exception ex)
{
...
}
}
}
What should I put in my MainWindow OnClosing Event?
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
....
base.OnClosing(e);
}
Upvotes: 3
Views: 272
Reputation: 80272
Personally, I'd publish an event from the OnClosing
using Reactive Extensions (RX) and a Subject
.
Everywhere in the program that I need it, I'd subscribe to the event and perform any cleanup.
This would decouple the OnClosing
event from all of the subscribers that do the cleanup, and would let you place the cleanup code for the database and the heavy lifting code for the database close to each other.
Upvotes: 1
Reputation: 1668
Take a bool variable IsTaskCompleted
in your class and keep default value to false
. As a last statement in the try
block of your task, set IsTaskCompleted
to true
.
Check this variable in the closing event handler, if value is false
that means task isn't got completed.
Upvotes: 1