BeginAcceptTcpClient线程安全吗? C#

问题描述 投票:0回答:1

我开始在TCP Asynchronous服务器的世界,寻找一种方法来处理几个连接,同时我发现BeginAcceptTcpClient可能是一个解决方案。

我发现有两种方法可以在服务器启动时使用BeginAcceptTcpClient来接收连接。我的问题是:这两者之间的区别是什么,哪一个是线程安全的(或两者都是)。

第一种方式

在回调中调用BeginAcceptTcpClient

static TcpListener socket = new TcpListener(IPAddress.Any, 4444);

public static void InitNetwork()
        {
            socket.Start();
            socket.BeginAcceptTcpClient(new AsyncCallback(OnClientConnect), null);
        }

private static void OnClientConnect(IAsyncResult ar)
        {
            TcpClient newclient = socket.EndAcceptTcpClient(ar);
            socket.BeginAcceptTcpClient(new AsyncCallback (OnClientConnect), null); // Call the Callback again to continue listening

            HandleClient.CreateConnection(newclient); //Do stuff with the client recieved
        }

第二种方式

使用AutoResetEvent

static TcpListener socket = new TcpListener(IPAddress.Any, 4444);
private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);

public static void InitNetwork()
        {
            socket.Start();

            while(true)
            {
              socket.BeginAcceptTcpClient(new AsyncCallback(OnClientConnect), null);
              connectionWaitHandle.WaitOne(); // Wait until a client has begun handling an event
              connectionWaitHandle.Reset(); // Reset wait handle or the loop goes as fast as it can (after first request)
            }

        }

private static void OnClientConnect(IAsyncResult ar)
        {
            TcpClient newclient = socket.EndAcceptTcpClient(ar);
            connectionWaitHandle.Set(); //Inform the main thread this connection is now handled

            HandleClient.CreateConnection(newclient);  //Do stuff with the client recieved
        }

我正在寻找正确的方法来处理多个连接(线程安全)。我很感激任何答案。

c# .net multithreading tcp
1个回答
0
投票

我更喜欢AcceptTcpClientAsync。它比BeginAcceptTcpClient更简单,仍然是异步的。

public async Task InitNetwork()
{
    while( true )
    {
        TcpClient newclient = await socket.AcceptTcpClientAsync();
        Task.Run( () => HandleClient.CreateConnection( newclient ) );
    }
}

在内部,AcceptTcpClientAsync使用Task.Factory.FromAsyncBeginAcceptTcpClientEndAcceptTcpClient包装成Task对象。

public Task<TcpClient> AcceptTcpClientAsync()
{
    return Task<TcpClient>.Factory.FromAsync(BeginAcceptTcpClient, EndAcceptTcpClient, null);
}
© www.soinside.com 2019 - 2024. All rights reserved.