Once you go async, you need to go async all the way to the top. But you need to always return an awaitable (commonly a Task
).
Exception made for event handlers and method overrides. But in this case those will be fire-and-forget.
What's hapening in your code is that, although inside your authenticateUser
(which, by convention, should be called AuthenticateUserAsync
) method you are awaiting for the result of GetMyData (again, GetMyDataAsync
), you are not returning any awaitable results to the caller. Becaus aysnc methods return to the caller as soon as they hit the first await
statement.
Because of that, when ApplicationBarDone_Click
calls userDAO.authenticateUser
it imediately returns because it's not awaitable.
If you can't change authenticateUser
, you simply can't use async-await
. But being Windows Phone, network calls need to be asynchronous and you need to change that. Being so, your AuthenticateUserAsync
method (remember the convention?) should look something like this:
public async override Task<string> AuthenticateUserAsync(string login, string password, string clientkey, string systemurl)
{
string url = systemurl + "/rest/user?login=" + login + "&password=" + password + "&clientkey=" + clientkey + "&languageId=" + 1;
return await GetMyDataAsync(url);
}
And your ApplicationBarDone_Click
should look something like this:
private async void ApplicationBarDone_Click(object sender, EventArgs e)
{
bool isValid = checkForValidation();
if (isValid)
{
string url = txtUrl.Text.ToString().TrimStart(' ').TrimEnd(' ');
string login = txtLogin.Text.ToString().TrimStart(' ').TrimEnd(' ');
string clientKey = txtSystemKey.Text.ToString().TrimStart(' ').TrimEnd(' ');
string psw = txtPassword.Text.ToString().TrimStart(' ').TrimEnd(' ');
RestfulWebServiceUserDAO userDAO = new RestfulWebServiceUserDAO();
string result = await userDAO.AuthenticateUserAsync(login, psw, clientKey, url);
// do whatever you need to do after login.
// just remember that, during the call to userDAO.AuthenticateUserAsync
// the UI is responsive and the user can click again
}
}
To learn more about asyn-await
programming, read my curation.