我正在编写一个套接字服务器并尝试利用新async / await
功能。
我的代码基于这个 stackoverflow 答案
我明白了
mscorlib.dll 中出现“System.OutOfMemoryException”类型的未处理异常
在下面的代码中有什么明显的人可以看到的吗?
public void Main()
{
CancellationTokenSource cts = new CancellationTokenSource();
TcpListener listener = new TcpListener(IPAddress.Any, 6666);
listener.Start();
while (true)
{
AcceptClientsAsync(listener, cts.Token);
}
cts.Cancel();
listener.Stop();
}
async Task AcceptClientsAsync(TcpListener listener, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
TcpClient client = await listener.AcceptTcpClientAsync();
Console.WriteLine("Client. Doing the do.");
SomeTaskAsync(client, ct);
}
}
async Task SomeTaskAsync(TcpClient client, CancellationToken ct)
{
var stream = client.GetStream();
while (!ct.IsCancellationRequested)
{
// Do Stuff
stream.Close();
client.Close();
}
}