I would like to handle long running work in a separate thread and return control back to the ASAP GUI thread using the async / await template as follows:
private async void Button_Click(object sender, RoutedEventArgs e) { await Test(); txtResult.Text = "Done!"; } private Task Test() { Thread.Sleep(3000); return Task.FromResult(0); }
The problem is that it freezes the GUI in any case for 3 seconds (it stops responding until Done! Is displayed after 3 seconds). What am I doing wrong?
EDIT: I am trying to replace the following logic:
private void Button_Click(object sender, RoutedEventArgs e) { var thread = new Thread(() => Test(Callback)); thread.Start(); } private void Callback() { Dispatcher.Invoke(() => txtResult.Text = "Done!"); } private void Test(Action callback) { Thread.Sleep(3000);
In the actual project, I have a different long logic than just "Sleep", and it still freezes the GUI, so replacing it with Task.Delay does not solve anything. Also, I don't understand why you should use another command to sleep? How is this required when designing async / wait?
source share