title: How can I wait for my async operations to finish when the application gets exited using?
body: <p>If a user performs an operation, such as deleting items, it removes them from the UI right away and then deletes them from the database on a background thread using TPL. The problem is if the user exits the application before the background thread finishes, the item never actually gets deleted.</p>
  
  <p>Is there a standard way of waiting for async operations to finish before shutting down the application?</p>
  
  <p>My async calls look like this:</p>
  
  <pre><code>if (MyObjectList.Contains(obj)) MyObjectList.Remove(obj);
  Task.Factory.StartNew(() =&gt; DAL&lt;MyEntities&gt;.DeleteObject(obj));
  </code></pre>
  
  <p><strong>Update</strong></p>
  
  <p>Here's the final code I went with. I'm quite happy to see it works as it should, although let me know if I can improve it. I still have a lot to learn :)</p>
  
  <pre><code>public partial class App : Application
  {
      private List&lt;Task&gt; _backgroundTasks = new List&lt;Task&gt;();
  
      public App()
      {
          EventSystem.Subscribe&lt;TaskStartedMessage&gt;((e) =&gt;
          {
              _backgroundTasks.Add(e.Task);
          });
  
          EventSystem.Subscribe&lt;TaskEndedMessage&gt;((e) =&gt;
          {
              if (_backgroundTasks.Contains(e.Task))
                  _backgroundTasks.Remove(e.Task);
          });
      }
  
      protected override void OnExit(ExitEventArgs e)
      {
          Task.WaitAll(_backgroundTasks.Where(p =&gt; !p.IsCompleted).ToArray(), 30000);
  
          base.OnExit(e);
      }
  }
  </code></pre>
  
  <p>And when starting an important background task, I'm using this syntax:</p>
  
  <pre><code>var task = Task.Factory.StartNew(() =&gt; DAL&lt;MyEntities&gt;.DeleteObject(obj));
  EventSystem.Publish&lt;TaskStartedMessage&gt;(new TaskStartedMessage(task));
  await task;
  EventSystem.Publish&lt;TaskEndedMessage&gt;(new TaskEndedMessage(task));
  </code></pre>
  
  <p>I'm using AsyncCTP for <code>await</code>/<code>async</code>, and Microsoft Prism's <code>EventAggregator</code> for the event system.</p>