C# UWP 套接字:使用 ReceiveAsync / SendAsync 并在不关闭套接字的情况下处理超时

C# UWP Socket: using ReceiveAsync / SendAsync and handling a timeout without closing the socket

我正在 UWP 平台上编写一个 class 库,它将在移动 UWP 应用程序中使用。

库需要通过基于 TCP 的专有协议与外部设备通信。 该协议要求接收或发送操作等待准确的时间。

我实际上已经使用 ReceiveAsync 和 SendAsync 实现了通信层,"await"正如 TPL 模式所建议的那样。

在大量阅读该论点之后,我发现无法在 read/write 操作上本地设置超时。 可以使用一些技巧来实现超时过程(例如:.WaitAny 或可超时标记)但我所有的阅读都让我明白了这个事实:

只有关闭套接字才能中断 ReceiveAsync 或 SendAsync 任务

我的问题是:这是真的吗? 一个timeout倒是Receive/Send只能阻塞closing/disposing这个socket?

如果这是真的,因为我正在实施的协议不允许我 open/close 套接字数百次,我需要恢复同步 Receive/Send 实际处理正常超时的命令版本

我已经阅读了很多关于参数的内容并且我很确定我所写的内容,但老实说我希望有一种方法可以使用 TPL 模式来处理超时而无需关闭套接字...

谢谢。

My question is: is this true? A timeout'd Receive/Send can be blocked only closing/disposing the socket?

是的,没错。超时不适用于异步套接字方法。取消现有异步 read/write 的正确方法是关闭套接字。

If this is true, as the protocol I'm implementing doesn't allow me to open/close the socket hundreds of time, I need to revert back to the sync Receive/Send version of the command that actually handle graceful timeout.

我不同意。协议定义中的超时只是建议性的;它们不能被强制执行。或者换句话说,它不一定是 文字 接收或发送超时;它可以是 逻辑 "receive" 或 "send" 超时。