Setting shutdown mode to OnMainWindowClose so that all pending tasks will terminate when closing the main window.
Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;