A "deadlock" occurs when HttpClient is used to simulate concurrent calls when a client calls an API "?, Httpclientapi
I usually prefer reading books .. But sometimes I often feel confused when I encounter problems .. IQ really hurts ..
The Code is as follows:
Class Program {static void Main (string [] args) {HttpClientClass c = new HttpClientClass (); while (true) {Task. factory. startNew () => {Console. writeLine (Thread. currentThread. managedThreadId + "Start request:" + DateTime. now); c. beginGetMethod () ;}, CancellationToken. none, TaskCreationOptions. none, TaskScheduler. default); System. threading. thread. sleep (10*1) ;}} public class HttpClientClass {private static readonly HttpClient c; static HttpClientClass () {c = new HttpClient (); c. timeout = TimeSpan. fromSeconds (15);} public void BeginGetMethod () {try {var r = c. getAsync (" https://www.cnblogs.com/ "). Result; if (r. isSuccessStatusCode) Console. writeLine (Thread. currentThread. managedThreadId + "OK"); else Console. writeLine (Thread. currentThread. managedThreadId + "bad request");} catch (Exception ex) {Console. writeLine (ex. getType (). fullName );}}
The query is blocked after the HttpClient GetAsync request is used. the Result is "deadlocked". We know that GetAsync is also being executed by a background thread. When the Result is obtained, the SetResult method in the Task is called and then passed. the Result is returned ..
If there is a problem here, wouldn't it be useless if concurrent requests come during website development ?!!
Of course not .. In fact, when processing tasks in the thread pool, there is a task queue (not to mention the source code .. Forget it after reading it ..) This generally means that when the main thread creates a thread task, the task priority is higher than the thread created by the background thread. Here, while does not stop creating background tasks, which leads to the background tasks in the GetAsync method being waiting .. So there is a so-called "deadlock ".. In fact, there is no chance to execute it .. (Thread context switching is not involved, so when talking about this, it can also cause a deadlock ..)
So you can call this method as follows:
Task. factory. startNew () => {while (true) {Task. factory. startNew () => {Console. writeLine (Thread. currentThread. managedThreadId + "Start request:" + DateTime. now); c. beginGetMethod () ;}, CancellationToken. none, TaskCreationOptions. none, TaskScheduler. default); System. threading. thread. sleep (10*1 );}});