0

So I am currently experementing with Sockets and I want to have 3 ports open for client sockets to connect to. So this works if I manually add my threads.

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();
....

But I want to do it a bit cleaner so I tried with a for loop

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

The socket server does fully work but when I work with threads and add them manually. If I work with a for loop, the socket server with the port becomes unavailable. Probably because the thread is stopped and I fail to understand why.

Note: SyncServer is a static class and StartListening is a static method. If I use a for loop, they always get the latest portnumber (in this case 11003).

Wojtek322
  • 584
  • 7
  • 20
  • Related: [Captured variable in a loop in C#](https://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp) – Theodor Zoulias Nov 22 '20 at 19:40

1 Answers1

4

I guess it is related to a classic "lambda function in a for loop" issue.

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);
}
Vlad DX
  • 4,200
  • 19
  • 28
  • 1
    What the hell, that indeed does the job. Thank you so much and I have never ever seen that before. I guess the i value gets overridden before the socket is fully setup. And innerI gets created each time on a new memory location. – Wojtek322 Nov 22 '20 at 16:15