Why is my async ASP.NET Web API controller blocking the main thread?

前端 未结 2 980
庸人自扰
庸人自扰 2021-01-12 17:22

I have an ASP.NET Web API controller that I would have thought would operate asynchronously. The controller is designed to sleep 20 seconds for the first request, b

相关标签:
2条回答
  • 2021-01-12 18:00

    This actually has nothing to do with the server, and everything to do with the client. Both Chrome and Firefox don't appear to want to send what they deem a "duplicate" request until the first one has its response. A separate "private" session of either browser will return from the second request immediately. Internet Explorer 9 doesn't seem to exhibit this behaviour.

    To isolate from client implementations, I put together the following client.

    class Program
    {
        static void Main(string[] args)
        {
            var t1 = Task.Run(() => FetchData(1));
            var t2 = Task.Run(() => FetchData(2));
            var t3 = Task.Run(() => FetchData(3));
    
            var index = Task.WaitAny(t1, t2, t3);
            Console.WriteLine("Task {0} finished first", index + 1);
    
            Task.WaitAll(t1, t2, t3);
            Console.WriteLine("All tasks have finished");
    
            Console.WriteLine("Press any key");
            Console.ReadKey(true);
        }
    
        static void FetchData(int clientNumber)
        {
            var client = new WebClient();
            string data = client.DownloadString("http://localhost:61852/api/values");
            Console.WriteLine("Client {0} got data: {1}", clientNumber, data);
        }
    }
    

    It's output goes:

    1. Client 2 got data: "FOOBAR" (within milliseconds of startup)
    2. Client 3 got data: "FOOBAR"
    3. Task 2 finished first
    4. (long wait here)
    5. Client 1 got data: "FOOBAR"
    6. All tasks have finished
    0 讨论(0)
  • 2021-01-12 18:03

    In my case here is output (it switches to another thread from 5 to 10):

    Entry thread id: 5. Sync: System.Web.LegacyAspNetSynchronizationContext
    Sleepy thread id: 10. Sync: 
    Finished sleeping
    The thread '<No Name>' (0x2c84) has exited with code 0 (0x0).
    Entry thread id: 7. Sync: System.Web.LegacyAspNetSynchronizationContext
    The thread '<No Name>' (0x1818) has exited with code 0 (0x0).
    Entry thread id: 5. Sync: System.Web.LegacyAspNetSynchronizationContext
    The thread '<No Name>' (0xd4c) has exited with code 0 (0x0).
    The thread '<No Name>' (0x2c30) has exited with code 0 (0x0).
    

    This could be due to environment and machine running (single core) that makes the runtime decide how to run it.

    0 讨论(0)
提交回复
热议问题