Async and UI Thread - davidortinau/ControlGallery GitHub Wiki
💬 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 voidmethods 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, buttonClicked, etc.) that:- Use
Thread.Sleep, longfor/whileloops, or repeated synchronous I/O (e.g.,File.ReadAllText,Directory.GetFiles, etc.) - Perform heavy LINQ queries or parsing on large data collections
- Use
✅ Fix Examples
❌ Bad:
var result = service.GetDataAsync().Result; // blocks UI thread
✅ Good:
var result = await service.GetDataAsync();
🛠 Suggested Review Steps
- Search your project for blocking calls:
.Result,.Wait(,GetAwaiter().GetResult() - Convert them to
awaitwhere possible and propagate async upstream - Identify synchronous logic in UI thread entry points like
OnAppearing,Page.Loaded,Button.Clicked - Move blocking or heavy operations (e.g., loops, file I/O, LINQ on large data sets) into
Task.Runor 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