我的多线程HttpClient是否存在任何问题? [英] Are there any issues with my multithreaded HttpClient?

查看:121
本文介绍了我的多线程HttpClient是否存在任何问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在尝试使用Java和HttpClient之后,我决定过渡到C#以尝试在提高速度的同时降低内存使用量.我一直在阅读成员在此处提供的有关异步与多线程的大量文章.看来多线程将是更好的方向.

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 provided by members on here regarding async vs multithreading. It appears multithreading would be the better direction.

我的程序将访问服务器并一遍又一遍地发送相同的请求,直到检索到200个代码为止.原因是因为在高峰时段流量很高.这使得服务器非常难以访问,并引发5xx错误.该代码非常简单,我不想添加循环以帮助简化查看器.

My program will be accessing a server and sending the same requests over and over until a 200 code is retrieved. Reason being is because during peak hours the traffic is very high. It makes the server is VERY hard to reach and throws 5xx errors. The code is very bare, I didn't want to add the loop yet to help with simplicity for the viewers.

我觉得自己正在朝着正确的方向前进,但我想与社区建立联系,以摆脱任何不良习惯.再次感谢您阅读.

I feel that I am heading towards the right direction but I would like to reach out to the community to break out of any bad habits. Thanks again for reading.

主持人的注意事项:我要检查我的代码是否有差异,我很清楚,多线程HttpClient可以.

Note to moderators: I am asking to check my code for discrepancies, I am well aware that it's okay to multithread 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();
        }
    }
}

此外,我不确定这是否重要,但是我正在MacBook Pro上运行它,并计划在BeagleBoard上运行它.

Also, I am not sure if it matters but I am running this on my MacBook Pro and plan to run it on my BeagleBoard.

推荐答案

如果我是你,这就是我要怎么做.我将尽可能多地利用异步,因为它比使用线程更有效(您很可能不必一直在上下文切换,这很昂贵).

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
    }
}

请注意,我确实同意@Damien_The_Unbeliever:如果服务器在高负载下出现问题,则不应添加不必要的负载(执行相同请求的X倍)并助长服务器的问题.理想情况下,您将修复服务器代码,但我知道它不是您的.

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.

这篇关于我的多线程HttpClient是否存在任何问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆