c# - Calling async method synchronously -
i have async method:
public async task<string> generatecodeasync() { string code = await generatecodeservice.generatecodeasync(); return code; } i need call method synchronous method.
how can without having duplicate generatecodeasync method in order work synchronously?
update
yet no reasonable solution found.
however, see httpclient implements pattern
using (httpclient client = new httpclient()) { // async httpresponsemessage responseasync = await client.getasync(url); // sync httpresponsemessage responsesync = client.getasync(url).result; }
you can access result property of task, cause thread block until result available:
string code = generatecodeasync().result; note: in cases, might lead deadlock: call result blocks main thread, thereby preventing remainder of async code execute. have following options make sure doesn't happen:
- add
.configureawait(false)library method or explicitly execute async method in thread pool thread , wait finish:
string code = task.run(generatecodeasync).result;
Comments
Post a Comment