c# - How to return the Task<T> from HttpResponseMessage.Content.ReadAsStringAsync().ContinueWith() method? -
i trying get/post using httpclient class , facing following issues
- do not know how return task httpresponsemessage.content.readasstringasync().continuewith() method.
for reason, keep on cancelling automatically
private static task<t> httpclientsendasync<t>(string url, object data, httpmethod method, string contenttype, cancellationtoken token) { httprequestmessage httprequestmessage = new httprequestmessage(method, url); retrydelegatinghandler retrydelegatinghandler = new retrydelegatinghandler(); retrydelegatinghandler.preauthenticate = true; retrydelegatinghandler.credentials = credential; retrydelegatinghandler.proxy = null; httpclient httpclient = new httpclient(retrydelegatinghandler); httpclient.timeout = new timespan(constants.timeout); if (data != null) { byte[] bytearray = encoding.ascii.getbytes(helper.tojson(data)); memorystream memorystream = new memorystream(bytearray); httprequestmessage.content = new stringcontent(new streamreader(memorystream).readtoend(), encoding.utf8, contenttype); } task<httpresponsemessage> httpresponsemessage = httpclient.sendasync(httprequestmessage); httpresponsemessage.continuewith((task) => { if (!task.isfaulted) { httpresponsemessage response = task.result; response.content.readasstringasync().continuewith( (stringtask) => { if (!stringtask.isfaulted) { return helper.fromjson<t>(stringtask.result); } else { logger.log(string.format("sendasyncrequest task isfaulted: {0} \nexception: {1}", typeof(t), task.exception)); updateerror(typeof(t).tostring()); return default(t); } }); } else { logger.log(string.format("sendasyncrequest task isfaulted: {0} \nexception: {1}", typeof(t), task.exception)); updateerror(typeof(t).tostring()); return default(t); } }); }
update: work still not work while trying handle fault.
return httpclient.sendasync(httprequestmessage).continuewith(task => { var response = task.result; return response.content.readasstringasync().continuewith(stringtask => { var json = stringtask.result; return helper.fromjson<t>(json); }); }).unwrap();
task.continuewith
returns continuation task: task
or task<t>
. if i'm understanding question, in case here this:
var continuation = httpresponsemessage.continuewith((task) => { if (!task.isfaulted) { httpresponsemessage response = task.result; return response.content.readasstringasync().continuewith( (stringtask) => { ...
and continuation
end being task<task<t>>
can call .unwrap()
on turn proxy task task<t>
.
Comments
Post a Comment