簡體   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