【问题标题】:Thread pool not working as expected [duplicate]线程池未按预期工作[重复]
【发布时间】:2014-01-27 22:04:15
【问题描述】:

我正在尝试使用套接字连接进行简单的 tcp 端口扫描,并且我正在使用线程池,但我没有得到我期望的输出,线程池的代码来自 here

我的代码:

IPAddress dstIpAddress ;
IPAddress.TryParse("192.168.2.106", out dstIpAddress);
Action<IPAddress,int> tcpConnect = (( dstIp,  destinationPort) => 
{
    string result = "open";
    try
    {
        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sock.Connect(dstIpAddress, destinationPort);
    }
    catch (Exception e)
    {
        result = "closed";
    }
    Console.WriteLine("TCP port {0} is {1}.", destinationPort, result);
});

using (var pool = new ThreadPool(10))
{
    for (var i = 0; i < 50; i++)
    {
        pool.QueueTask(() => tcpConnect(dstIpAddress,i));
    }
}

【问题讨论】:

  • 使用 Resharper 将提示您显式捕获 var。很棒的工具

标签: c# multithreading


【解决方案1】:

i 变量开始被捕获,而不是它的值。将循环更改为:

for (var i = 0; i < 50; i++)
{
  int port = i;
  pool.QueueTask(() => tcpConnect(dstIpAddress,port));
}

【讨论】:

    【解决方案2】:

    因为在循环完成后,除了一个排队的任务外,所有任务都在运行,所以当它们运行时,i 始终为 50。您需要获取循环变量的本地副本:

    for (var i = 0; i < 50; i++)
    {
        var port = i;
    
        pool.QueueTask(() => tcpConnect(dstIpAddress, port));
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多