title: How to close modal window after a Task completes?
body: <p>I have two default windows. <strong>I want one window starts a work, shows another window in the modal (dialog) form (progress indicating, but now it is not important), then closes it after this work has been finished.</strong> I have the following problems in my implementation:</p>
  
  <p>1) after the work completes ("Completed!" message box shows up, but it also is not important and is just indication), the ProgressWindow doesn't close automatically;</p>
  
  <p>2) if I close it by clicking manually the red cross, the System.InvalidOperationException with the message "The calling thread cannot access this object because a different thread owns it." occurs at the line</p>
  
  <pre><code>await task;
  </code></pre>
  
  <p>3) the code in ContinueWith actually is performed BEFORE the Go method finishes - why?</p>
  
  <p>How can I achieve such a behavior?</p>
  
  <p>My implementation:</p>
  
  <pre><code>namespace WpfApp1
  {
      public partial class MainWindow : Window
      {
          public MainWindow()
          {
              InitializeComponent();
          }
  
          async void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
          {
              Window w = new ProgressWindow();
  
              var task = 
                  Task
                  .Run(() =&gt; Go())
                  .ContinueWith(completedTask =&gt; w.Close());
              w.ShowDialog();
              await task; // InvalidOperationException throws
          }
  
          async protected void Go()
          {
              await Task.Delay(500); // imitate some work    
              MessageBox.Show("Completed!"); // indicate that work has been completed
          }
      }
  }
  </code></pre>