0

Hi, I have this code here

if (Main && List && Admin)
{
Console.WriteLine("[SERVER]" + "Waiting to connect");
TcpClient ClientList = ListServer.AcceptTcpClient();
if (ClientList.Connected)
{
    Console.ForegroundColor = ConsoleColor.Green;
    Console.WriteLine(ListMessage + "CONECTED !");
}
NextCode();
      }
  }

 private void NextCode()
{
//CODE
}

When you come to the line: TcpClient ClientList = ListServer.AcceptTcpClient();. The program waits for a connection. How do I stop waiting in the background and further lines of code to perform?

user3310916
  • 1
  • 1
  • 3

2 Answers2

3

AcceptTcpClient is a blocking call. You will either need to move your connection listening work in to a separate thread, or use Asyc method calls to accept connections without blocking.

Bradley Uffner
  • 16,641
  • 3
  • 39
  • 76
0

use a Background Worker:

//define this outside
TcpClient ClientList;

//....
    if (Main && List && Admin)
    {
        Console.WriteLine("[SERVER]" + "Waiting to connect");
        bw.RunWorkerAsync();

        NextCode();
    }

}

private void NextCode()
{
    //CODE
}

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    ClientList = ListServer.AcceptTcpClient();
}

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (ClientList.Connected)
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(ListMessage + "CONECTED !");
    }
}
Alejandro del Río
  • 3,966
  • 3
  • 33
  • 31