繁体   English   中英

BeginAcceptTcpClient线程安全吗? C#

[英]Is BeginAcceptTcpClient thread safe? C#

我开始在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
        }

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

我更喜欢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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM