Check completion of async task from another thread
I am using async tasks to download files and update the database. I need to know when the application is closed to update the download state in the DB.
My task is in the ViewModel class.
private async void OnUpload(object param)
{
await Task.Factory.StartNew(() =>
{
try
{
...
}
catch (Exception ex)
{
...
}
}
}
What should I include in the MainWindow OnClosing event?
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
....
base.OnClosing(e);
}
Take the bool variable IsTaskCompleted
in your class and keep the default false
. try
Set IsTaskCompleted
in as the last statement in your task block true
.
Check this variable in your close event handler if the value false
indicates that the task has not completed.
Personally, I would post an event from OnClosing
using Reactive Extensions (RX) and Subject
.
Everywhere in the program I need, I signed up for the event and performed any cleanup.
This will cancel the event OnClosing
from all subscribers doing the cleanup and allow you to put the cleanup code for the database and the heavy load code for the database close to each other.