.NET: How can I keep using a socket after a read timeout?

丶灬走出姿态 提交于 2019-12-13 04:48:47

问题


In my application, I want to have a polling loop which blocks on a socket receive operation but times out after 100 ms. This would allow me to exit the loop when I want (e.g. the user clicks something in the UI) while avoiding using a busy loop or Thread.sleep.

However, it seems that once a .NET socket is opened, it can only time out once. After the first timeout, any calls that would block throw an exception immediately.

According to this question, "you can’t timeout or cancel asynchronous Socket operations." Why not? Is there a better way to approach the problem in the .NET world?


回答1:


To write a non-busy polling loop on a .NET socket, you can use the Poll socket method, as follows:

for (keepGoing) {
    if (mySocket.Poll(1000 * timeout_milliseconds, SelectMode.SelectRead)) {
        // Assert: mySocket.Available > 0.
        // TODO: Call mySocket.Receive or a related method
    }
}

In this case, Poll returns false if no data becomes available to read from the socket within the specified timeout. Another thread can reset keepGoing to false if it wants to cleanly shut down the polling loop.



来源:https://stackoverflow.com/questions/10591235/net-how-can-i-keep-using-a-socket-after-a-read-timeout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!