为什么我在我的 C# 服务中收到这个 SocketException?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/557879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:05:49  来源:igfitidea点击:

Why am I getting this SocketException in my C# service?

c#sockets

提问by user65266

I have a service that is responsible for reading and writing from a server. The reading and writing is done in different threads.

我有一个负责从服务器读取和写入的服务。读取和写入在不同的线程中完成。

The reader thread is active all the time whereas write thread only activates to send message and dies once message is written to server and response is received.

读取线程始终处于活动状态,而写入线程仅激活发送消息并在消息写入服务器并收到响应后死亡。

The service runs for 4 days and after that I am getting this error continuously, whenever the service tries to read from the port:

该服务运行 4 天后,每当该服务尝试从端口读取时,我都会不断收到此错误:

System.Net.Sockets.SocketException: An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full

System.Net.Sockets.SocketException:无法对套接字执行操作,因为系统缺少足够的缓冲区空间或队列已满

采纳答案by twk

This can happen when you establish a large number of outgoing connections very quickly and run out of local ports. You can read about the "ephemeral port range" here.

当您非常快速地建立大量传出连接并用完本地端口时,就会发生这种情况。您可以在此处阅读有关“临时端口范围”的信息

Or, you may simply be running out of sockets. Make sure you closethem after you are done using them.

或者,您可能只是用完了套接字。确保在使用它们后关闭它们。

回答by Steve Wranovsky

I would also strongly suggest you look at your write thread, and how you are referencing resources related to the Socket. Ie, are you calling Close/Dispose for any NetworkStream or other objects you are using with the Socket? A code sample from the write thread would be helpful if you're still struggling with the problem.

我还强烈建议您查看您的写线程,以及您如何引用与 Socket 相关的资源。即,您是否为与 Socket 一起使用的任何 NetworkStream 或其他对象调用 Close/Dispose?如果您仍然在为该问题苦苦挣扎,那么来自 write 线程的代码示例会有所帮助。

You might also want to monitor the process memory and handle usage through the task manager.

您可能还想通过任务管理器监视进程内存并处理使用情况。