Asynchronous method starts AsyncCallback in the current thread (main thread)

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)
    {
         //Receiving messages from the client
    }
}

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.

+6
source share
1 answer

, , , AsyncCallback . , , , .

, , BeginXXX , , , , . , , IAsyncResult.CompletedSynchronously true , while (true), BeginAcceptTcpClient .

, .

async/await, .

+2

All Articles