There is a server of class TcpListener. It accepts incoming connections using the BeginAcceptTcpClient (AsyncCallback, Object) method.
Code written in MSDN example
public static ManualResetEvent tcpClientConnected =
new ManualResetEvent(false);
public static void DoBeginAcceptTcpClient(TcpListener
listener)
{
while(true)
{
tcpClientConnected.Reset();
Console.WriteLine("Waiting for a connection...");
listener.BeginAcceptTcpClient(
new AsyncCallback(DoAcceptTcpClientCallback),
listener);
tcpClientConnected.WaitOne();
}
}
public static void DoAcceptTcpClientCallback(IAsyncResult ar)
{
TcpListener listener = (TcpListener) ar.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(ar);
Console.WriteLine("Client connected completed");
tcpClientConnected.Set();
while(true)
{
}
}
The problem is that the DoAcceptTcpClientCallback (IAsyncResult ar) method sometimes runs in the current thread (main), and not in the new one, and blocks it (main). Because of this, the following compounds cannot be obtained. Please help understand why not create a thread for this method.
source
share