I've been trying to learn async coding recently. I've managed to get it to work and the UI thread doesn't block like it does if I don't make the code async. I realise this is a very contrived example, but is this how async should be done?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
string outputString = (await Authentication(usernameTextBox.Text)) ? "Name exists" : "Name does not exist";
MessageBox.Show(outputString);
}
private Task<bool> Authentication(string username)
{
return Task.Run(() => CheckIfNameExistsInDatabaseOnServer(username));
}
private bool CheckIfNameExistsInDatabaseOnServer(string username)
{
//Pretend to pass details and wait for a response
Thread.Sleep(5000);
return (username == "Will");
}
}