Skip to content

Async and UI Thread

David Ortinau edited this page Apr 10, 2025 · 4 revisions

πŸ’¬ Copilot Chat Prompt

Review my .NET MAUI code for async/await issues. Look for .Result, .Wait(), GetAwaiter().GetResult(), and any long-running synchronous methods on the UI thread. Suggest how to convert blocking code to async/await correctly.

Validate Async Code and UI Thread Usage

Misuse of async/await is one of the most common causes of UI hangs in .NET MAUI apps.

πŸ” What to Look For

  • Use of .Result, .Wait(), or .GetAwaiter().GetResult() β€” these block the UI thread
  • async void methods not attached to UI events β€” these are hard to monitor and can crash the app
  • Synchronous methods triggered from UI lifecycle or interaction events (OnAppearing, OnNavigatedTo, button Clicked, etc.) that:
    • Use Thread.Sleep, long for/while loops, or repeated synchronous I/O (e.g., File.ReadAllText, Directory.GetFiles, etc.)
    • Perform heavy LINQ queries or parsing on large data collections

βœ… Fix Examples

❌ Bad:

var result = service.GetDataAsync().Result; // blocks UI thread

βœ… Good:

var result = await service.GetDataAsync();

πŸ›  Suggested Review Steps

  1. Search your project for blocking calls: .Result, .Wait(, GetAwaiter().GetResult()
  2. Convert them to await where possible and propagate async upstream
  3. Identify synchronous logic in UI thread entry points like OnAppearing, Page.Loaded, Button.Clicked
  4. Move blocking or heavy operations (e.g., loops, file I/O, LINQ on large data sets) into Task.Run or dedicated background threads

πŸ”Ž Example: Heavy work on UI thread

❌ Bad:

protected override void OnAppearing()
{
    base.OnAppearing();
    for (int i = 0; i < 10000; i++)
    {
        var contents = File.ReadAllText($"data_{i}.txt");
    }
}

βœ… Good:

protected override async void OnAppearing()
{
    base.OnAppearing();
    await Task.Run(() =>
    {
        for (int i = 0; i < 10000; i++)
        {
            var contents = File.ReadAllText($"data_{i}.txt");
        }
    });
}

➑️ Next: Audit Layout Complexity

πŸ“š Additional Resources

Clone this wiki locally