Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 异步套接字服务器中的OutOfMemoryException_C#_Sockets_Async Await_Cancellationtokensource - Fatal编程技术网

C# 异步套接字服务器中的OutOfMemoryException

C# 异步套接字服务器中的OutOfMemoryException,c#,sockets,async-await,cancellationtokensource,C#,Sockets,Async Await,Cancellationtokensource,我正在编写socket服务器程序。它将侦听特定的IP和端口。一旦数据进入,处理数据并将其存储在数据库中。 我希望我的程序无论数据是否输入都能全天候收听。如果出现,则处理它,否则等待新客户端加入 下面是示例代码 static async Task AcceptClientsAsync(TcpListener listener, CancellationToken ct) { try { var clientCounte

我正在编写socket服务器程序。它将侦听特定的IP和端口。一旦数据进入,处理数据并将其存储在数据库中。 我希望我的程序无论数据是否输入都能全天候收听。如果出现,则处理它,否则等待新客户端加入

下面是示例代码


static async Task AcceptClientsAsync(TcpListener listener, CancellationToken ct) { try { var clientCounter = 0; while (!ct.IsCancellationRequested) { TcpClient client = await listener.AcceptTcpClientAsync().ConfigureAwait(true); clientCounter++; EchoAsync(client, clientCounter, ct); } } catch (Exception e) { NewLog.WriteErrorLogToBuffer("exception in AcceptClientsAsync " + e.InnerException, false); } }
它工作正常,但一段时间后我的内存出现异常。有什么办法可以解决这个问题吗?

您的TcpClient实例永远不会被释放,因此它们将保持打开状态,直到您的程序内存耗尽并被操作系统关闭

您需要在使用完TcpClient后关闭它。最好的方法是将其包装在using块中:

另一种方法是使用其Close方法手动关闭它,但请注意,如果在调用关闭TcpClient之前引发异常,则TcpClient将永远保持打开状态

using(TcpClient client = await listener.AcceptTcpClientAsync().ConfigureAwait(true))
{
    clientCounter++;
    EchoAsync(client, clientCounter, ct);
}