![](/img/trans.png)
[英]C# Tcp BeginAcceptTcpClient throws ObjectDisposedException
[英]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.FromAsync
將BeginAcceptTcpClient
和EndAcceptTcpClient
包裝到Task對象中。
public Task<TcpClient> AcceptTcpClientAsync()
{
return Task<TcpClient>.Factory.FromAsync(BeginAcceptTcpClient, EndAcceptTcpClient, null);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.