-1

I have a WPF application (C# 6.0, .NET 6.1, Visual Studio 2015, x64) that freezes the interface when I start the following task:

private async void ComputeButton_Click(object sender, RoutedEventArgs e) {
  await Scanner();
  DrawButtons();
}

private static async Task Scanner() {
  try {
    BigBox.DoScan();
    await Task.CompletedTask;
  } catch (Exception ex) {
    SMErrorLog.WriteLog("Scanner error: ", ex);
  }
}

My application consists of several tabs. The above code is in one of the tabs. If I click on the "Compute" button, the computation proceeds (for several minutes), but I cannot select any of the other tabs to do something else while the computation proceeds. I assume the code above is asynchronous and I don't understand why the application freezes while the DoScan runs.

Any help or suggestions will be greatly appreciated.

Charles

H.B.
  • 166,899
  • 29
  • 327
  • 400
CBrauer
  • 1,035
  • 2
  • 11
  • 17
  • What does `BigBox.DoScan` do? what is `Task.CompletedTask`? – L.B Oct 11 '16 at 17:29
  • BigBox.DoScan is a library routine that scans a SQL Server 2016 database. It looks at about 2000 tables looking for unusual patterns. – CBrauer Oct 11 '16 at 17:37
  • Task.CompletedTask is in the Microsoft Task library. – CBrauer Oct 11 '16 at 17:40
  • 1
    `I assume the code above is asynchronous` You assume incorrectly. – Servy Oct 11 '16 at 17:46
  • See also http://stackoverflow.com/questions/21348125/how-to-execute-task-in-the-wpf-background-while-able-to-provide-report-and-allow, https://stackoverflow.com/questions/21419229/c-sharp-threading-async-running-a-task-in-the-background-while-ui-is-interactab, https://stackoverflow.com/questions/15879375/highly-responsive-multi-threaded-wpf-application, and https://stackoverflow.com/questions/26367548/returning-from-a-task-without-blocking-ui-thread, to name just a few similar questions on Stack Overflow – Peter Duniho Oct 11 '16 at 19:58

1 Answers1

1

In order to make your UI responsive with asynchronous you need to execute BigBox.DoScan() on a new Task and then wait for it to finish with the await keyword, because these occurs on a different Task the UI will not freeze:

 private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        await Scanner();
    }

  private static async Task Scanner()
    {
        try
        {
            await Task.Run(() =>
            {
                 BigBox.DoScan();
            });

        }
        catch (Exception ex)
        {
           SMErrorLog.WriteLog("Scanner error: ", ex);
        }
    }
Rom
  • 1,183
  • 1
  • 8
  • 18