c# - How can avoid set my method as async when I'm using ReadAsStringAsync()? -


i'm developing library c# , .net framework 4.0.

i have method put on asp.net web api 2 web service.

public async task<string> prepareandstartv2(     string ordernumber,     string username,     string systemname) {     string uri =         string.format(prepareandstarturi, ordernumber, username, systemname);      string batchname = null;      using (var client = new httpclient())     {         client.baseaddress = new uri(webapihost);         client.defaultrequestheaders.accept.clear();         client.defaultrequestheaders.accept.add(new mediatypewithqualityheadervalue("application/json"));          httpcontent content = new stringcontent(string.empty, encoding.utf8, "application/json");          task<httpresponsemessage> response = client.putasync(uri, content);         httpresponsemessage message = response.result;          task<string> task = message.content.readasstringasync();          batchname = await task;     }      return batchname; } 

i added message.content.readasstringasync() string returned method. , after i've been forced , task<string>, await , async everywhere.

is there option read string in httpcontent without using await, task<string> , async?

maybe running task inside prepareandstartv2 method wait i'm reading string readasstringasync().

you can use task.result after calling async method avoid own method forced async:

public string prepareandstartv2(     string ordernumber,     string username,     string systemname) {     string uri =         string.format(prepareandstarturi, ordernumber, username, systemname);      string batchname = null;      using (var client = new httpclient())     {         client.baseaddress = new uri(webapihost);         client.defaultrequestheaders.accept.clear();         client.defaultrequestheaders.accept.add(new mediatypewithqualityheadervalue("application/json"));          httpcontent content = new stringcontent(string.empty, encoding.utf8, "application/json");          httpresponsemessage message = client.putasync(uri, content).result;         batchname = message.content.readasstringasync().result;     }      return batchname; } 

Comments