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);
}

      

+3


source to share


2 answers


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.

+1


source


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.

+1


source







All Articles