Stack overflow when using the System.Net.Sockets.Socket.AcceptAsync model

后端 未结 4 1636
太阳男子
太阳男子 2021-02-13 10:44

With respect to C# and .NET\'s System.Net.Sockets.Socket.AcceptAsync method, one would be required to handle a return value of \"false\" in order to handle the immediately avail

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-13 11:13

    I have resolved this problem by simply changing the placement of the loop. Instead of recursively calling the accept handler from within itself, wrapping the code in a do-while loop with the condition being "!Socket.AcceptAsync(args)" prevents a stack overflow.

    The reasoning behind this is that you utilize the callback thread for processing the connections which are immediately available, before bothering to asynchronously wait for other connections to come across. It's re-using a pooled thread, effectively.

    I appreciate the responses but for some reason none of them clicked with me and didn't really resolve the issue. However, it seems something in there triggered my mind into coming up with that idea. It avoids manually working with the ThreadPool class and doesn't use recursion.

    Of course, if someone has a better solution or even an alternative, I'd be happy to hear it.

提交回复
热议问题