问题描述
限时送ChatGPT账号..在我的应用程序中,我想要一个轮询循环,该循环阻塞套接字接收操作,但在 100 毫秒后超时.这将允许我在需要时退出循环(例如用户单击 UI 中的某些内容),同时避免使用繁忙循环或 Thread.sleep.
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.
不过,好像.NET socket一旦打开,就只能超时一次.第一次超时后,任何会阻塞的调用都会立即抛出异常.
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.
根据这个问题,你不能超时或取消异步 Socket
操作."为什么不?在 .NET 世界中是否有更好的方法来解决这个问题?
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?
推荐答案
要在.NET socket上写一个非忙轮询循环,可以使用Poll socket方法,如下:
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
}
}
在这种情况下,如果在指定的超时时间内没有可从套接字读取的数据,Poll
将返回 false.如果另一个线程想要彻底关闭轮询循环,则可以将 keepGoing
重置为 false.
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.
这篇关于.NET:如何在读取超时后继续使用套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论