I am getting myself confused about async void
and button handlers. I heard in a video tutorial that it was not wise to use async void
. I have reviewed these questions:
In many answers it does actually use this syntax. Thus my confusion. 🧐
Here is my handler:
async private void InstallStyleButton_Clicked(object sender, EventArgs e)
{
var customFileType =
new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<string>>
{
{DevicePlatform.macOS, new[] {"xsl"} }
});
var pickResult = await FilePicker.PickAsync(new PickOptions
{
FileTypes = customFileType,
PickerTitle = "Select template to install"
});
if(pickResult != null)
{
// Build target path
string targetFile = Path.Combine("/Users/Shared/VisitsRota.MacOS/Styles", pickResult.FileName);
// OK to install?
if(!File.Exists(targetFile))
{
// Install
File.Copy(pickResult.FullPath, targetFile);
// Add it
StylesPicker.ItemsSource.Add(pickResult.FileName);
// Select it
StylesPicker.SelectedItem = pickResult.FileName;
}
}
}
I realise it is not a good idea to hardcode the folder path and I will eventually get around to that. Other than that, my handler appears to operate fine on my development MacBook Pro when I try it.
Is my use of async void
with the button handler ok? And if not, how should my handler be adjusted?
I found this link where it states:
To summarize this first guideline, you should prefer
async Task
toasync void
.Async Task
methods enable easier error-handling, composability and testability. The exception to this guideline is asynchronous event handlers, which must returnvoid
.
So my code is OK.