UI threading in .NET
Here is a simple WPF program with nine buttons. Each button is supposed to run the code below, which takes a couple of seconds, and report when it's done.
private void PerformCalculation()
{
// Placeholder calculation
for (int i = int.MinValue; i < int.MaxValue; i++) ;
}
Try to work out how each button will behave before clicking the blurred description to reveal it. Will the interface remain repsonsive? Will an exception be raised? Will the program crash?
Button 1
private void Button1_Click(object sender, RoutedEventArgs e)
{
PerformCalculation();
TextBox.AppendText("Done");
}
Behaviour:
Button 2
private async void Button2_Click(object sender, RoutedEventArgs e)
{
await Task.Run(() => PerformCalculation());
TextBox.AppendText("Done");
}
Behaviour:
Button 3
private async void Button3_Click(object sender, RoutedEventArgs e)
{
await Task.Run(() =>
{
PerformCalculation();
TextBox.AppendText("Done");
});
}
Behaviour:
Button 4
private void Button4_Click(object sender, RoutedEventArgs e)
{
Task.Run(() =>
{
PerformCalculation();
TextBox.AppendText("Done");
});
}
Behaviour:
Button 5
private async void Button5_Click(object sender, RoutedEventArgs e)
{
await Task.Run(() => PerformCalculation()).ConfigureAwait(false);
TextBox.AppendText("Done");
}
Behaviour:
Button 6
private async void Button6_Click(object sender, RoutedEventArgs e)
{
var syncContext = SynchronizationContext.Current;
await Task.Run(() =>
{
PerformCalculation();
syncContext.Post(_ => TextBox.AppendText("Done"), null);
});
}
Behaviour:
Button 7
private async void Button7_Click(object sender, RoutedEventArgs e)
{
await Task.Run(() =>
{
PerformCalculation();
Dispatcher.Invoke(() => TextBox.AppendText("Done"));
});
}
Behaviour:
Button 8
private async void Button8_Click(object sender, RoutedEventArgs e)
{
await Task.Run(() => PerformCalculation());
MessageBox.Show("Done");
}
Behaviour:
Button 9
private async void Button9_Click(object sender, RoutedEventArgs e)
{
await Task.Run(() =>
{
PerformCalculation();
MessageBox.Show("Done");
});
}
Behaviour: