Are there any issues with my multithreaded HttpClient?

后端 未结 4 1826
走了就别回头了
走了就别回头了 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:26

    Here is how I would do it if I were you. I would leverage async as much as possible as it's much more efficient than using Threads (you most likely won't have to context-switch all the time which is expensive).

    class MainClass
    {
        public static HttpClient client = new HttpClient();
        static string url = "http://www.website.com";
    
        public static async Task getSessionAsync()
        {
            StringContent queryString = new StringContent("{json:here}");
    
            // Send a request asynchronously continue when complete
            using (HttpResponseMessage result = await client.PostAsync(url, queryString))
            {
                // Check for success or throw exception
                string resultContent = await result.Content.ReadAsStringAsync();
                Console.WriteLine(resultContent);
            }
        }
    
        public static async Task RunAsync()
        {
            await getSessionAsync();
            // Not yet implemented yet..
            //doMore ();
        }
    
        public static void Main(string[] args)
        {
            Console.WriteLine("Welcome!");
    
            const int parallelRequests = 5;
            // Send the request X times in parallel
            Task.WhenAll(Enumerable.Range(1, parallelRequests).Select(i => RunAsync())).GetAwaiter().GetResult();
    
            // It would be better to do Task.WhenAny() in a while loop until one of the task succeeds
            // We could add cancellation of other tasks once we get a successful response
        }
    }
    

    Note that I do agree with @Damien_The_Unbeliever: if the server has issues under heavy load, you shouldn't be adding unnecessary load (doing X times the same request) and contribute to the server's issues. Ideally you'd fix the server code but I can understand that it's not yours.

提交回复
热议问题