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

2019-09-03 09:40发布

问题:

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.