How can I wait for my async operations to finish when the application gets exited using? How can I wait for my async operations to finish when the application gets exited using? wpf wpf

How can I wait for my async operations to finish when the application gets exited using?


There is no standard way but since you create a specific Task here it should be easy to put that in a List and build some Exit-logic to Wait for all Tasks in that List.

OK, a sample. Untested and incomplete:

// untestedstatic class CriticalTasks{    static HashSet<Task> tasks = new HashSet<Task>();    static object locker = new object();    // when starting a Task    public static void Add(Task t)    {        lock(locker)           tasks.Add(t);    }    // When a Tasks completes    public static void Remove(Task t)    {        lock(locker)           tasks.Remove(t);    }    // Having to call Remove() is not so convenient, this is a blunt solution.     // call it regularly    public static void Cleanup()    {        lock(locker)           tasks.RemoveWhere(t => t.Status != TaskStatus.Running);    }    // from Application.Exit() or similar.     public static void WaitOnExit()    {        // filter, I'm not sure if Wait() on a canceled|completed Task would be OK        var waitfor = tasks.Where(t => t.Status == TaskStatus.Running).ToArray();        Task.WaitAll(waitfor, 5000);    }}


The drawback is that you will have to extend each Task with the code to Add & Remove it.

Forgetting a Remove() (eg when an Exception happens) would be a (small) memory-leak. It is not too critical, instead of burdening your code with using() blocks you could also periodically run a Cleanup() method that uses HashSet.RemoveWhere() to remove non-running tasks.


var x = Task.Factory.StartNew(() => DAL<MyEntities>.DeleteObject(obj));

In form close event:

while(!x.IsCompleted){hide form}

Or

if(!x.IsCompleted)   //cancel exit


You could store reference to your Task, and wait for it when application is quitting (on Exit events for example).

You could also create a normal thread, make sure you set IsBackground to false (default value). Process will not quit until all non-background threads will finish their work, so it will run to the end, you will have to watch out not to use any GUI logic or make sure that you will not dispose objects that you need from this thread.