I’m working on an app for Windows 8. I have a C# class called “User”. User has a method called authenticate. My method looks something like this:
public class User
{
public bool IsAuthenticated { get; set; }
public async void Authenticate(string username, string password)
{
// Code to build parameters and url is here
var response = await httpClient.PostAsync(myServiceUrl, new StringContent(json, String.Text.Encoding.UTF8, "application/json"));
JsonObject result = JsonObject.Parse(await response.Content.ReadAsStringAsync());
}
}
The Authenticate method works. Its successfully hitting my service and returning the appropriate details. My question is, how do I detect when this method has completed? I’m calling this method in response to a user clicking a “Login” button in my app. For instance, something like this:
private void loginButton_Click(object sender, RoutedEventArgs e)
{
User user = new User();
user.IsAuthenticated = false;
user.Authenticate(usernameTextBox.Text.Trim(), passwordBox.Password.Trim());
if (user.IsAuthenticated)
{
// Allow the user to enter
}
else
{
// Handle the fact that authentication failed
}
}
Essentially, I need to wait for the authenticate method to complete its execution. But, I don’t know how to do this. What am I doing wrong?
Thank you
First, you need to make
Authenticate()returnTaskinstead ofvoid.The returned
Task(which is generated by the compiler) will give you information about the status of the asynchronous operation.You need to make the event handler method
asynctoo.You can then
awaitthe result of your otherasyncmethod.In general, you should never use
async voidmethods except as event handlers.