Are there any issues with my multithreaded HttpClient?

后端 未结 4 1825
走了就别回头了
走了就别回头了 2021-02-04 16:47

So after dabbling with Java and HttpClient, I\'ve decided to transition to C# to try and lower the memory usage while increasing speed. I\'ve been reading tons of articles provi

4条回答
  •  无人及你
    2021-02-04 17:40

    Reading the docummentation of HttpClient:

    Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

    Don't take risks. Have a separate HTTP client per thread.

    It seems that you are blocking the thread waiting for the reply and you are doing it from a thread that does not do anything extra. Then why bother with async/await? You can use plain simple blocking calls.

    Also - your program now finishes immediately after starting the threads. You might want to wait for the threads to finish before returning from main. You can do that by this code at the end of your program:

    Thread1.Join();
    Thread2.Join();
    

    Update based on comments:

    1. Decide how many parallel requests you want to make - this will be your number of threads.
    2. Make main thread wait for signal using ManualResetEvent.
    3. In each thread keep submitting your requests. As soon as you get answer that you are waiting for - signal the ManualResetEvent and allow your main function to return.

提交回复
热议问题