-
Notifications
You must be signed in to change notification settings - Fork 7
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.
Misuse of async/await is one of the most common causes of UI hangs in .NET MAUI apps.
- 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
β Bad:
var result = service.GetDataAsync().Result; // blocks UI threadβ Good:
var result = await service.GetDataAsync();- 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
β 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");
}
});
}