AcceptTcpClient阻塞其余代码

时间:2014-02-26 16:18:08

标签: c# tcpclient

嗨,我这里有这段代码

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
}

当你走到界限时:TcpClient ClientList = ListServer.AcceptTcpClient();。程序等待连接。如何停止在后台等待以及执行更多代码?

2 个答案:

答案 0 :(得分:3)

AcceptTcpClient是一个阻塞调用。您将需要将连接侦听工作移动到单独的线程中,或者使用Asyc方法调用来接受连接而不会阻塞。

答案 1 :(得分:0)

使用后台工作人员:

//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 !");
    }
}