Now I think I understand why this happening so I guess my question is how can I modify the code to act how I want.
First the code.
private void btnLiveSignin_Click(object sender, RoutedEventArgs e)
{
var LoggedIn = Login();
busy.Visibility = System.Windows.Visibility.Visible; // Display the please wait message
if (LoggedIn.Result)
{
// Do something
}
}
public async Task<bool> Login()
{
try
{
var e = await lac.InitializeAsync(Scopes);
if (e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
// do some stuff now that we are connected
return true;
}
else
{
// not connected so do something
return false;
}
}
catch (Exception ex)
{
return false;
}
}
Basically when the user clicks a button it will log them in to their windows live account and while that is happening a message appears asking the user to please wait.
As you can guess the UI locks so the message never appears. How can I change it so the UI doesn't lock?
I done this with windows phone 7.5 before using events as the sdk didn't use async, and that worked perfectly fine. Would this require a mixture of asyncing and events?
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.