I have two default windows. 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. I have the following problems in my implementation:
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;
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
await task;
3) the code in ContinueWith actually is performed BEFORE the Go method finishes - why?
How can I achieve such a behavior?
My implementation:
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(() => Go())
.ContinueWith(completedTask => 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
}
}
}
ShowDialog
block? How would you ever know the task completed without the user closing the dialog anyway? I'm thinking you need to pass the task to the dialog as a parameter andawait
it somewhere there. The window can close itself when the task is completed.