我不知道如何在异步方法等待传入连接时正确关闭 TcpListener。 我在 SO 上找到了这段代码,这里是代码:
public class Server
{
private TcpListener _Server;
private bool _Active;
public Server()
{
_Server = new TcpListener(IPAddress.Any, 5555);
}
public async void StartListening()
{
_Active = true;
_Server.Start();
await AcceptConnections();
}
public void StopListening()
{
_Active = false;
_Server.Stop();
}
private async Task AcceptConnections()
{
while (_Active)
{
var client = await _Server.AcceptTcpClientAsync();
DoStuffWithClient(client);
}
}
private void DoStuffWithClient(TcpClient client)
{
// ...
}
}
主要内容:
static void Main(string[] args)
{
var server = new Server();
server.StartListening();
Thread.Sleep(5000);
server.StopListening();
Console.Read();
}
这一行抛出异常
await AcceptConnections();
当我调用 Server.StopListening() 时,对象被删除。
所以我的问题是,如何取消 AcceptTcpClientAsync() 以正确关闭 TcpListener。
最佳答案
由于这里没有合适的工作示例,这里有一个:
假设您在范围内同时拥有 cancellationToken
和 tcpListener
,那么您可以执行以下操作:
using (cancellationToken.Register(() => tcpListener.Stop()))
{
try
{
var tcpClient = await tcpListener.AcceptTcpClientAsync();
// … carry on …
}
catch (InvalidOperationException)
{
// Either tcpListener.Start wasn't called (a bug!)
// or the CancellationToken was cancelled before
// we started accepting (giving an InvalidOperationException),
// or the CancellationToken was cancelled after
// we started accepting (giving an ObjectDisposedException).
//
// In the latter two cases we should surface the cancellation
// exception, or otherwise rethrow the original exception.
cancellationToken.ThrowIfCancellationRequested();
throw;
}
}
关于c# - TcpListener : how to stop listening while awaiting AcceptTcpClientAsync()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19220957/