c# - Issue creating HttpClient helper method -
i have functioning async task calls web service:
private async task getresult() { using (var client = new httpclient()) { client.baseaddress = new uri(_baseaddress); client.defaultrequestheaders.accept.clear(); client.defaultrequestheaders.accept.add( new mediatypewithqualityheadervalue("application/json")); client.defaultrequestheaders.add("username", _username); client.defaultrequestheaders.add("action", "get"); /* etc */ var response = await client.getasync(client.baseaddress); } }
i separate out creation of httpclient object can parameterized , reused:
private async task getresult() { using (var client = getclient(_baseaddress, _username)) { var response = await client.getasync(client.baseaddress); } } private static httpclient getclient(string address, string username) { using (var client = new httpclient()) { client.baseaddress = new uri(address); client.defaultrequestheaders.accept.clear(); client.defaultrequestheaders.accept.add( new mediatypewithqualityheadervalue("application/json")); client.defaultrequestheaders.add("username", username); client.defaultrequestheaders.add("action", "get"); /* etc */ return client; } }
while appears functionally identical me, latter throws aggregateexception
error inner exception
cannot access disposed object. object name: 'system.net.http.httpclient'.
perhaps there async subtlety don't understand?
get rid of using
inside of getclient
. use using
things remain "in ownership", "giving ownership caller" when return client;
.
it caller's resposability use using
statement (which correctly in getresult
).
this has nothing asnyc , standard idisposable
behavior.
Comments
Post a Comment