【问题标题】:Why is using multiple threads not improving performance?为什么使用多个线程不能提高性能?
【发布时间】:2017-08-18 19:15:40
【问题描述】:

所以我一直在尝试使用 c# WebClient。我设法用类似这样的代码制作了一个工作程序(控制台应用程序):

static void Search(string number)
{
    using (var client = new WebClient())
    {
        for (int a = 0; a < globalvariable.lenght; a++)
        {
            string toWrite = "nothing";
            for (int b = 0; a < globalvariable2.lenght; b++)
            {
                string result = client.DownloadString(urlString);
                //do stuff with toWrite if page is not empty
                //change toWrite and break the b loop
            }
            Console.WriteLine(toWrite);
        }
    }
}

它并不是真的很快,所以我想我可以通过使用多个线程来让它更快。 执行需要 2 分钟。

所以我尝试将循环设为Parallel.For 循环。执行仍然需要 2 分钟。所以我在这里阅读了一些东西并编写了以下代码:

static async Task AWrite(string number, int a) 
{
    using (var client = new WebClient())
    {
        string toWrite = "nothing";
        for(int b=0; a<globalvariable2.lenght; b++)
        {
            string result = await client.DownloadStringTaskAsync(uri);
            //do stuff with toWrite if page is not empty
            //change toWrite and break the b loop
        }
        Console.WriteLine(toWrite);
    }
}

然后调用它的函数:

private static void ASearch(string number)
{
    var tasks = new List<Task>();
    for(int a=0; a<gobalvariable.Length; a++)
    {
        tasks.Add(AWrite(number, a));
    }
    Task.WaitAll(tasks.ToArray());
}

所以我认为多个WebClient 会同时下载字符串,显然这不会发生,因为这也需要两分钟才能执行。这是为什么?通过在控制台中写入,我知道它们没有按顺序执行,但仍然需要相同的时间。如何通过使用多线程来实际提高第一个函数的性能?

【问题讨论】:

  • 我认为 Web 客户端一次只能处理 1 个请求。
  • 一个我肯定只能处理一个。但是由于我基本上是在不同的线程上使用多个客户端,这些多个客户端不能发出多个请求吗?
  • 一个任务可能会映射到不同的线程,也可能不会。
  • 所以您是说每个 webclient 请求可能在同一个线程上执行?如果是这样,有什么办法可以改变吗?编辑:每次都是(通常是 23 个)?
  • @nix 您正在做的工作不是 CPU 绑定的工作,而是 IO 绑定的工作。 没有线程 在该 IO 发生时正在使用。只需要一个线程来发送初始请求(并且您只需要一个线程)并在获得响应后处理响应(如果没有同步上下文,您在技术上允许在多个线程上发生,但这是一个你正在做的工作的一小部分)。网络连接处理并发请求的能力与 CPU 上运行的线程以及它们正在做什么无关。

标签: c# multithreading webclient


【解决方案1】:

您可以更改 HTTP 连接限制:

System.Net.ServicePointManager.DefaultConnectionLimit = 5;

查看ServicePointManager.DefaultConnectionLimit 以及有关ServicePoint 课程的文章。使用此属性,您可以更改 HTTP 连接的默认连接限制。

【讨论】:

    【解决方案2】:

    最后,限制在我正在下载的站点中。它限制为每人 1 个 HTTP 连接。感谢您的想法。

    【讨论】:

      猜你喜欢
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多