c# - Avoiding Deadlock with HttpClient -


what best way use httpclient , avoid deadlock? using code below, called entirely synchronous methods, concerned maybe causing deadlock.

i've done reading on functions .configureawait(false), .getawaiter(), .getresult() looking input on best practice approach.

not quite exact code, close enough.

public static bool tryrequest(string url, out response) {         httpcontent content = new stringcontent(json, encoding.utf8, "application/json");     using (httpclient client = new httpclient())     {        httpresponsemessage responsemessage = null;         switch (verb)        {           case httpverb.put:              responsemessage = client.putasync(url, content).result;              break;           case httpverb.post:              responsemessage = client.postasync(url, content).result;              break;           case httpverb.delete:              responsemessage = client.deleteasync(url).result;              break;           case httpverb.get:              responsemessage =  client.getasync(url).result;              break;        }         if (responsemessage.issuccessstatuscode)        {           responsecontent = responsemessage.content.readasstringasync().result;           statuscode = responsemessage.statuscode;        }     } } 

it looks trying run asynchronous code synchronously.

with winforms , wpf you cannot safely this!

the thing can use async way up. known problem .net async. can use public async void xxx() methods. don't know when complete. should ever use async void when coupled event handler.

the reason getting deadlocks default taskfactory try marshal interupt callbacks synchronizationcontext, ui thread.

even if use task.configureawait(false) there no guarantee further down callstack don't have callback expects ui thread.

as long block synchronizationcontext thread, there high possibility deadlock.

it worth noting possible asynchronous code seems work. because, async method returns task, allowed synchronously complete (for example task.return<t>(t result)). happen methods have cache (like httprequests).

edit: @sriramsakthivel suggest can run async method synchronously wrapping within task.run. because task.run run code without parent synchronizationcontext.

task.run(runrequest).result;

i not recommend this, relies on specific implementation of task.run along taskfactory work. entirely possible (but unlikely) new version of .net break piece of code.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -