In my Xamarin.Forms application, I have some code that looks like this
private async void OnEntryLosesFocus(object sender, EventArgs e) {
var vm = (MainPageViewModel)BindingContext;
if (vm == null)
{
return;
}
if (!IsAnyNavButtonPressedOnUWP())
{
// CheckAndSaveData() causes dialogs to show on the UI.
// I need to ensure that CheckAndSaveData() completes its execution and control is not given to another function while it is running.
var _saveSuccessfulInUnfocus = await vm.CheckAndSaveData();
if (_saveSuccessfulInUnfocus)
{
if (Device.RuntimePlatform == Device.UWP)
{
if (_completedTriggeredForEntryOnUWP)
{
var navAction = vm.GetNavigationCommand();
navAction?.Invoke();
_completedTriggeredForEntryOnUWP = false;
}
}
else
{
vm._stopwatchForTap.Restart();
}
}
else
{
vm._stopwatchForTap.Restart();
}
}
}
The method above is an EventHandler
for the unfocus event for one of my entries. However due to the way Xamarin works when a button is clicked the Unfocused event is triggered before the Command attached is executed.
I need to ensure that the function vm.CheckAndSaveData()
finishes executing before the command attached to this button hence why I need to run it synchronously.
I have tried multiple things but they all result in deadlocks.
Some of the solutions I have tried are in this question: How would I run an async Task<T> method synchronously?
THEY ALL RESULT IN DEADLOCKS. There has to be some way I can run my function synchronously or at least force the function CheckAndSaveData
to finish before anything else.