.net - C# return from async task not working -
i'm working on async http call using httpclient. call made inside async task. call successful , response http call. when try return response task nothing happens, though have breakpoint waiting after return.
public void executetask(foundation.security.securitytoken token, order order) { executetaskasync(token, order).wait(); } public async task executetaskasync(foundation.security.securitytoken token, order order) { if (order != null) { log.info("starting export of order " + order.id.tostring()); bool success = await exportorder(order, token); if (!success) { log.error("failed export order id " + order.id.tostring()); } } } private async task<bool> exportorder(order order, foundation.security.securitytoken token) { try { responseobject response = await webservice.sendorder(new senderinformation(token), new receiverinformation(order, token)); if (response.success && response.status.equals("201", stringcomparison.ordinalignorecase)) { log.info(string.format("order ({0}) exported"), order.externalorderid); return true; } return false; } catch (exception e) { log.error(string.format("exception occured while exporting order ({0})", order.id), e); return false; } }
below code actual http call. marked last functional line comment "the code reach line. after nothing happens"
public task<responseobject> sendorder(senderinformation sender, receiverinformation receiver) { orderrequest request = new orderrequest(sender, receiver); return executerequest<orderrequest, responseobject>(request); } private async task<responsetype> executerequest<requesttype, responsetype> (requesttype request) requesttype : requestobject responsetype : class, responseobject, new() { try { using (var client = new httpclient()) { string xml = serializerequest(request); httpcontent content = new stringcontent(xml); content.headers.contenttype = new system.net.http.headers.mediatypeheadervalue("text/xml"); string requesturl = "url"; httpresponsemessage response = await client.postasync(requesturl, content).configureawait(false); // parse response if (response.issuccessstatuscode) { stream responsestream = await response.content.readasstreamasync(); responsetype responseobject = deserializeresponse<responsetype>(responsestream); if (responseobject != null) { responseobject.success = true; return responseobject; //the code reach line. after nothing happens } else { log.error("response not deserialized"); } } else { log.error("error during request, got status code " + response.statuscode); } } } catch (exception e) { log.error("something went wrong!", e); } return new responsetype() { success = false }; }
the problem on line:
executetaskasync(token, order).wait();
this causes deadlock: await
s in called method can't resume because ui thread blocked.
when use async code, must use way; never wait synchronously async task complete.
Comments
Post a Comment