I am developing a .NET MAUI application and have encountered a potential deadlock issue related to asynchronous programming. I’m seeking advice on how to properly use ConfigureAwait(false)
to avoid deadlocks and improve performance.
Problem Description
In my application, I have several async methods interacting with a ViewModel
for tasks such as data fetching, UI updates, and page navigation. Recently, I’ve noticed that certain UI interactions lead to deadlocks, causing the UI to become unresponsive and some operations to hang indefinitely.
Code Details
Here is a simplified version of my code:
XAML Code
<ScrollView Orientation="Both" FlowDirection="RightToLeft"
HorizontalOptions="Start"
x:Name="ItemsScroller"
Scrolled="ScrollView_Scrolled"
HorizontalScrollBarVisibility="Always">
<VerticalStackLayout>
<HorizontalStackLayout HeightRequest="48" BackgroundColor="#F5F6F7">
<!-- Header Labels -->
<Label Text="کد کالا" Style="{StaticResource LableStyle}" WidthRequest="150" FontAttributes="Bold"/>
<Label Text="کالا" Style="{StaticResource LableStyle}" WidthRequest="300" FontAttributes="Bold"/>
<Label Text="نرخ" Style="{StaticResource LableStyle}" WidthRequest="150" FontAttributes="Bold"/>
<Label Text="مصوبه" Style="{StaticResource LableStyle}" WidthRequest="200" FontAttributes="Bold"/>
<Label Text="تاریخ مصوبه" Style="{StaticResource LableStyle}" WidthRequest="100" FontAttributes="Bold"/>
<Label Text="شماره مصوبه" Style="{StaticResource LableStyle}" WidthRequest="100" FontAttributes="Bold"/>
<Label Text="موجودی" Style="{StaticResource LableStyle}" WidthRequest="100" FontAttributes="Bold"/>
</HorizontalStackLayout>
<CollectionView HorizontalScrollBarVisibility="Never" VerticalScrollBarVisibility="Never"
VerticalOptions="StartAndExpand"
SelectionMode="Multiple" SelectedItems="{Binding SelectedProduct, Mode=TwoWay}"
ItemsSource="{Binding Goods}"
x:Name="GoodsCollectionView">
<CollectionView.ItemTemplate>
<DataTemplate>
<HorizontalStackLayout HeightRequest="48">
<!-- Data Template for items -->
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Normal">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="{Binding Color}"/>
</VisualState.Setters>
</VisualState>
<VisualState Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="#C8E6FF"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<!-- Item Labels -->
<Label Text="{Binding ProductCode}" Style="{StaticResource LableStyle}" WidthRequest="150"/>
<Line Stroke="#DFDFE0" Y2="40" VerticalOptions="Center"/>
<Label Text="{Binding ProductName}" Style="{StaticResource LableStyle}" WidthRequest="300"/>
<Line Stroke="#DFDFE0" Y2="40" VerticalOptions="Center"/>
<Label Text="{Binding Rate, StringFormat='{0:N0}'}" Style="{StaticResource LableStyle}" WidthRequest="150"/>
<Line Stroke="#DFDFE0" Y2="40" VerticalOptions="Center"/>
<Label Text="{Binding MosavabeSharh}" Style="{StaticResource LableStyle}" WidthRequest="200"/>
<Line Stroke="#DFDFE0" Y2="40" VerticalOptions="Center"/>
<Label Text="{Binding MosavabeDate}" Style="{StaticResource LableStyle}" WidthRequest="100"/>
<Line Stroke="#DFDFE0" Y2="40" VerticalOptions="Center"/>
<Label Text="{Binding MosavabeNo, StringFormat='{0:N0}'}" Style="{StaticResource LableStyle}" WidthRequest="100"/>
<Line Stroke="#DFDFE0" Y2="40" VerticalOptions="Center"/>
<Label Text="{Binding MojodiVaghee, StringFormat='{0:N0}'}" Style="{StaticResource LableStyle}" WidthRequest="100"/>
</HorizontalStackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</VerticalStackLayout>
</ScrollView>
Code Behind
private async void ScrollView_Scrolled(object sender, ScrolledEventArgs e)
{
if (!onNavigated) return;
var scrollView = sender as ScrollView;
if (scrollView != null && scrollView.ScrollY >= scrollView.ContentSize.Height - scrollView.Height)
{
await _viewModel.RunIsBusyTaskAsync(async () =>
{
start += 49;
end += 49;
await _viewModel.UpdateDisplayedItems(true, start, end);
}).ConfigureAwait(false);
}
}
ViewModel
public async Task UpdateDisplayedItems(bool IsClear, int start, int end)
{
var result = await GoodToList(new ProductsRequest
{
Start = start,
End = end
}).ConfigureAwait(false);
if (result == null || !result.Any())
return;
if (IsClear)
{
MainThread.BeginInvokeOnMainThread(() =>
{
result.ForEach(Goods.Add);
var productcode = new HashSet<string>(product.Select(c => c.ProductCode));
var userItemss = result.Where(x => productcode.Contains(x.ProductCode));
AddRange(SelectedProduct, userItemss);
});
return;
}
else
{
Goods = new ObservableCollection<Good>(result);
var userItems = result.Where(x => product.Select(c => c.ProductCode).Contains(x.ProductCode));
SelectedProduct = userItems.Any() ? new ObservableCollection<object>(userItems) : new ObservableCollection<object>();
}
}
Base ViewModel
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Mopups.Services;
using POSApp.Views.Popups;
using System.Collections.ObjectModel;
namespace POSApp.ViewModel
{
public partial class BaseViewModel : ObservableObject
{
private bool IsBusy, SecondIsBusy;
private Loading loadingPopup;
public IAsyncRelayCommand<object> OpenBrowserCommand { get; private set; }
public IAsyncRelayCommand<object> MakePhoneCallCommand { get; private set; }
public BaseViewModel()
{
loadingPopup = new Loading();
OpenBrowserCommand = new AsyncRelayCommand<object>(OpenBrowserAsync);
MakePhoneCallCommand = new AsyncRelayCommand<object>(MakePhoneCallAsync);
}
public async Task RunIsBusyTaskAsync(Func<Task> awaitableTask)
{
if (IsBusy) return;
IsBusy = true;
try
{
await MopupService.Instance.PushAsync(loadingPopup);
await awaitableTask();
}
catch (Exception) { }
finally
{
if (MopupService.Instance.PopupStack.Any())
await MopupService.Instance.PopAsync();
IsBusy = false;
}
}
public async Task AnimationClicked(object sender)
{
if (sender is VisualElement animatable)
{
await animatable.ScaleTo(0.75, 100);
await animatable.ScaleTo(1, 100);
}
}
public void AddRange<T>(ObservableCollection<T> collection, IEnumerable<T> items)
{
foreach (var item in items)
{
collection.Add(item);
}
}
}
}
Issue
Despite using ConfigureAwait(false)
in the UpdateDisplayedItems
method, I am still experiencing deadlocks and unresponsive UI elements. The deadlock occurs particularly when handling async operations triggered by UI interactions, such as scrolling.
Questions
- How should I effectively use
ConfigureAwait(false)
to avoid deadlocks in the context of a .NET MAUI application? - Are there any additional best practices for handling async operations in a MAUI application to prevent UI freezes and ensure smooth performance?
- Is there a specific area in my code where deadlocks might be occurring, and how can I diagnose and fix them?
Any insights or recommendations would be greatly appreciated.
Thank you!