patterncsharpMinor
First time trying async
Viewed 0 times
asyncfirsttryingtime
Problem
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 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");
}
}Solution
There isn't much to review here, but I would probably have introduced a variable for the
That said
I realize it's a tiny little example, but you have everything done in the UI's code-behind here - that's only good for prototype/throw-away code (which this probably is). In a real app you would have coded the logic elsewhere.
awaited call's result, and then used a ternary to determine the outputString; the difference would have been that the awaited call would have stood out more, but there's nothing really wrong with the way you did it.That said
outputString would probably be better off as outputMessage, or simply output - having the type name in an identifier is never a sign of great naming.I realize it's a tiny little example, but you have everything done in the UI's code-behind here - that's only good for prototype/throw-away code (which this probably is). In a real app you would have coded the logic elsewhere.
Context
StackExchange Code Review Q#74757, answer score: 6
Revisions (0)
No revisions yet.