What you're missing from your handler is async
and await
.
Because you marked your Login
method as async and made it return a task, you've made it awaitable, which makes it possible to re-write your event-handler as:
private async void btnLiveSignin_Click(object sender, RoutedEventArgs e)
{
var loginTask = this.Login();
busy.Visibility = System.Windows.Visibility.Visible;
await loginTask;
if(loginTask.Result)
{
// Do something
}
}
Marking the event-handler as async
indicates to the caller that it will complete asynchronously. What await
does is "signal" that you want to wait for the task to complete before continuing. Together this means that the event-handler can return an "incomplete" result back to the dispatcher (the UI thread) which will run in the background without disrupting the UI.
As a rule, once you start using async
and await
in your code, you should try using them "all the way down".
async
and await
are a bit devious in how the compiler turns them into "real" code, so don't be surprised if you need to read more around the topic to understand them fully.