c# - Async with HTTPClient -


i'm calling web api httpclient in app wp8. when click button user credentials , if it's ok go main page. code:

calling method

private async void btnlogin_onclick(object sender, routedeventargs e) {     var user = new user();      if (user.isauthenticated(tbusername.text, tbpassword.text))     {         navigationservice.navigate(new uri("/mainpage.xaml"));     } } 

user class

public class user {     private bool? _isauthenticated;     public bool isauthenticated(string _username, string _password)     {         return (bool)  (_isauthenticated ?? (_isauthenticated = authenticateasync(_username, _password).result));     }      private static async task<bool> authenticateasync(string username, string password)     {         var baseurl = string.format(constant.authenticateapiurl, username, password);         try         {             var client = new httpclient { baseaddress = new uri(baseurl) };             var result = await client.postasync(baseurl, new stringcontent("")).configureawait(false);                             result.ensuresuccessstatuscode();         }         catch (httprequestexception ex)         {             return false;         }         return true;     } } 

the problem when await executed, blocks app , never returns.

i try lot of distinct codes think i'm lost now!!.

calling task<t>.result or task.wait on ui thread can cause deadlock explain in full on blog.

to fix it, replace every use of result or wait await

public async task<bool> isauthenticatedasync(string _username, string _password) {     return (bool) (_isauthenticated ?? (_isauthenticated = await authenticateasync(_username, _password))); }  private async void btnlogin_onclick(object sender, routedeventargs e) {     var user = new user();      if (await user.isauthenticatedasync(tbusername.text, tbpassword.text))     {         navigationservice.navigate(new uri("/mainpage.xaml"));     } } 

other notes:


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -