【问题标题】:Threads created in for loop does not work [duplicate]在 for 循环中创建的线程不起作用 [重复]
【发布时间】:2021-03-05 10:44:34
【问题描述】:

所以我目前正在使用套接字,我想打开 3 个端口供客户端套接字连接。因此,如果我手动添加我的线程,这将有效。

Thread t = new Thread(() => SyncServer.StartListening(new IPAddress(new byte[]{127,0,0,1}), port));
t.Start();
Thread t2 = new Thread(() => SyncServer.StartListening(new IPAddress(new byte[]{127,0,0,1}), port + 1));
t2.Start();
....

但我想让它更简洁一些,所以我尝试使用 for 循环

List<Thread> threads = new List<Threads>();
for(int i = 0; i<3;i++)
{
    Thread t = new Thread(() => SyncServer.StartListening(new IPAddress(new byte[]{127,0,0,1}), port + i));
    t.Start();
    threads.Add(t);
}

套接字服务器确实可以正常工作,但是当我使用线程并手动添加它们时。如果我使用 for 循环,带有端口的套接字服务器将不可用。可能是因为线程停止了,我不明白为什么。

注意:SyncServer 是一个静态类,而 StartListening 是一个静态方法。如果我使用 for 循环,它们总是得到最新的端口号(在本例中为 11003)。

【问题讨论】:

标签: c# multithreading sockets for-loop static


【解决方案1】:

我猜这与经典的“for 循环中的 lambda 函数”问题有关。

List<Thread> threads = new List<Threads>();
for(int i = 0; i<3;i++)
{
    // Copying the `i` value to another variable will help
    var innerI = i;
    Thread t = new Thread(() => SyncServer.StartListening(new IPAddress(new byte[]{127,0,0,1}), port + innerI));
    t.Start();
    threads.Add(t);
}

【讨论】:

  • 什么鬼,这确实可以。非常感谢你,我以前从未见过。我猜想在套接字完全设置之前 i 值会被覆盖。并且每次都会在一个新的内存位置创建 innerI。
猜你喜欢
  • 1970-01-01
  • 2017-10-02
  • 2014-11-03
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 2020-06-20
相关资源
最近更新 更多