c# - HttpClient - A task was cancelled? -
it works fine when have 1 or 2 tasks throws error "a task cancelled" when have more 1 task listed.
list<task> alltasks = new list<task>(); alltasks.add(....); alltasks.add(....); task.waitall(alltasks.toarray(), configuration.cancellationtoken); private static task<t> httpclientsendasync<t>(string url, object data, httpmethod method, string contenttype, cancellationtoken token) { httprequestmessage httprequestmessage = new httprequestmessage(method, url); httpclient httpclient = new httpclient(); 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); } 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(); }
there's 2 reasons taskcanceledexception
thrown:
- something called
cancel()
oncancellationtokensource
associated cancellation token before task completed. - the request timed out, i.e. didn't complete within timespan specified on
httpclient.timeout
.
my guess timeout. (if explicit cancellation, have figured out.) can more inspecting exception:
try { var response = task.result; } catch (taskcanceledexception ex) { // check ex.cancellationtoken.iscancellationrequested here. // if false, it's pretty safe assume timeout. }
Comments
Post a Comment