c# - WebClient UploadValuesTaskAsync -


here webclient class:

class mywebclient : webclient {     private cookiecontainer _cookiecontainer = new cookiecontainer();     public mywebclient(string url, string login, string password)     {         var data = new namevaluecollection             {                 { "username",  login},                 { "password",  password}             };        uploadvalues(new uri(url), data);     }     protected override webrequest getwebrequest(uri address)     {         webrequest request = base.getwebrequest(address);         if (request httpwebrequest)         {             (request httpwebrequest).cookiecontainer = _cookiecontainer;         }         return request;     } } 

and here sample, how want use it:

private mywebclient _client;  private void btnlogin_click(object sender, routedeventargs e) {      _client = new mywebclient("http://website/login.php", "account", "pw"); }  private async void btncontent_click(object sender, routedeventargs e) {      _client = await _client.downloadstringtaskasync("http://website"); } 

and question is.. mywebclient class, how can login async? hope able me, thank you!

you can move login logic outside constructor , use uploadvaluestaskasync method this:

class mywebclient : webclient {     //...     private readonly string m_uri;     private readonly string m_login;     private readonly string m_password;      public mywebclient(string url, string login, string password)     {         m_password = password;         m_login = login;         m_uri = url;     }      public async task login()     {         var data = new namevaluecollection         {             {"username", m_login},             {"password", m_password}         };         await uploadvaluestaskasync(new uri(m_uri), data);     }      //... } 

and use this:

private async void btnlogin_click(object sender, routedeventargs e) {      _client = new mywebclient("http://website/login.php", "account", "pw");      await _client.login(); } 

Comments