string - c# return data from Asynchronous function -


i have 2 methods

public void getemp() {     httpwebrequest request = (httpwebrequest)httpwebrequest.create(new system.uri("http://sdw2629/empservice/employeeinfo.svc/employee"));     request.method = "get";     request.contenttype = "application/json; charset=utf-8";      request.begingetresponse(new asynccallback(readwebrequestcallback), request);    } 

and

private void readwebrequestcallback(iasyncresult callbackresult) {     httpwebrequest myrequest = (httpwebrequest)callbackresult.asyncstate;     using (httpwebresponse myresponse = (httpwebresponse)myrequest.endgetresponse(callbackresult))     {         using (streamreader httpwebstreamreader = new streamreader(myresponse.getresponsestream()))         {             string results = httpwebstreamreader.readtoend();             //execute ui stuff on ui thread.                       }     } }   

here want return string "results" other method

string data= obj1.getemp() 

how can achieve this.. appriciated.. thanks

easiest way rewrite method using async, this:

public async task<string> getempasync() {     httpwebrequest request = (httpwebrequest)httpwebrequest.create(new system.uri("http://sdw2629/empservice/employeeinfo.svc/employee"));     request.method = "get";     request.contenttype = "application/json; charset=utf-8";     var response = await request.getresponseasync();     using (streamreader httpwebstreamreader = new streamreader(response.getresponsestream()))     {         string results = await httpwebstreamreader.readtoendasync();         //execute ui stuff on ui thread.         return results;     }  } 

then can result code this:

var results = await getempasync(); 

if using older version , don't have async, can in blocking way result:

public string getempblocking() {     httpwebrequest request = (httpwebrequest)httpwebrequest.create(new system.uri("http://sdw2629/empservice/employeeinfo.svc/employee"));     request.method = "get";     request.contenttype = "application/json; charset=utf-8";     var response = request.getresponse();     using (streamreader httpwebstreamreader = new streamreader(response.getresponsestream()))     {         string results = httpwebstreamreader.readtoend();         //execute ui stuff on ui thread.         return results;     } } 

and result this:

var results = getresultblocking(); 

Р.s. can consider using microsoft.bcl.async support async in earlier versions.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -