Are there any problems with my multithreaded HttpClient?

So, after discussing with Java and HttpClient, I decided to switch to C # to try to reduce memory usage while increasing speed. I have read many articles submitted by members here regarding async vs multithreading. Multithreading seems to be the best direction.

My program will access the server and send the same requests again and again until the 200 code is retrieved. The reason is that during peak hours the traffic is very high. This makes the server VERY inaccessible and throws 5xx errors. The code is very bare, I did not want to add a loop yet to help with simplicity for the audience.

I feel like I'm heading in the right direction, but I would like to appeal to the community to break out of any bad habits. Thanks again for reading.

Note for moderators: I ask you to check your code for discrepancies, I well know that this is good for multi-threaded HttpClient.

using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Threading;

namespace MF
{
    class MainClass
    {
        public static HttpClient client = new HttpClient();
        static string url = "http://www.website.com";

        public static void getSession() {
            StringContent queryString = new StringContent("{json:here}");

            // Send a request asynchronously continue when complete
            var result = client.PostAsync(new Uri(url), queryString).Result;

            // Check for success or throw exception
            string resultContent = result.Content.ReadAsStringAsync().Result;

            Console.WriteLine(resultContent);
        }
        public static void Run() 
        {
            getSession ();
          // Not yet implemented yet..
          //doMore ();
        }

        public static void Main (string[] args)
        {
            Console.WriteLine ("Welcome!");

            // Create the threads
            ThreadStart threadref1 = new ThreadStart(Run);
            ThreadStart threadref2 = new ThreadStart(Run);
            Console.WriteLine("In the main: Creating the threads...");
            Thread Thread1 = new Thread(threadref1);
            Thread Thread2 = new Thread(threadref1);

            // Start the thread
            Thread1.Start();
            Thread2.Start();
        }
    }
}

Also, I'm not sure if it matters, but I run it on my MacBook Pro and plan to run it on my BeagleBoard.

+4
source share
4 answers

This is how I would do it if I were you. I would use async as much as possible, since it is much more efficient than using Threads (you most likely will not have to switch context 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
    }
}

, @Damien_The_Unbeliever: , ( X ) . , , .

+7

HttpClient:

(Shared in Visual Basic) . .

. HTTP- .

, , , , . async/wait? .

, . , , . :

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

:

  • , - .
  • ManualResetEvent.
  • . , , ManualResetEvent .
+1

:

CancelPendingRequests
DeleteAsync
GetAsync
GetByteArrayAsync
GetStreamAsync
GetStringAsync
PostAsync
PutAsync
SendAsync

More details:

+1
source

Header transmission is not thread safe.

For example, replacing an OAuth access token with a new one is not thread safe. Before that right now with the Xamarin mobile app. I have a crash report in which one thread was changing headers while another thread was trying to execute a request.

+1
source

Source: https://habr.com/ru/post/1624053/


All Articles