简体   繁体   English

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

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

I'm writing a class library on UWP platform that is going to be used from a mobile UWP application. 我正在UWP平台上编写类库,该类库将用于移动UWP应用程序。

The library needs to talk with an external device through a proprietary protocol TCP-based. 该库需要通过基于TCP的专有协议与外部设备进行通讯。 The protocol requires Receive or Send operation to be waited for an exact amount of time. 该协议要求接收或发送操作要等待确切的时间。

I've actually implemented the communication layer with ReceiveAsync and SendAsync, "await"ing for them, as the TPL pattern suggets. 实际上,我已经使用ReceiveAsync和SendAsync实现了通信层,并为它们“等待” TPL模式指示。

After a lot of reading on the argument, I discover there's no way to set natively a timeout on read/write operations. 在对参数进行大量阅读之后,我发现无法自然地设置读/写操作的超时时间。 Some tricks can be used to implement the timeout process (es: .WaitAny or timeoutable tokens) but all my readings brings me to this fact: 可以使用一些技巧来实现超时过程(例如:.WaitAny或超时令牌),但是我的所有阅读使我明白了这一事实:

A ReceiveAsync or SendAsync task can be interrupted only closing the socket 仅关闭套接字,才能中断ReceiveAsync或SendAsync任务

My question is: is this true? 我的问题是:这是真的吗? A timeout'd Receive/Send can be blocked only closing/disposing the socket? 只能关闭/处置套接字才能阻止超时的接收/发送吗?

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. 如果是这样,则由于我正在实施的协议不允许我数百次打开/关闭套接字,因此我需要恢复到实际处理正常超时的命令的同步接收/发送版本

I have read a lot on the arguments and I'm quite sure of what I have written, but honestly I hope there's a way to handle the timeout using the TPL pattern without needing to close the socket... 我已经阅读了很多有关参数的文章,并且对所写的内容很确定,但是老实说,我希望有一种方法可以使用TPL模式处理超时,而无需关闭套接字...

Thanks. 谢谢。

My question is: is this true? 我的问题是:这是真的吗? A timeout'd Receive/Send can be blocked only closing/disposing the socket? 只能关闭/处置套接字才能阻止超时的接收/发送吗?

Yes, that is correct. 对,那是正确的。 Timeouts don't apply to asynchronous socket methods. 超时不适用于异步套接字方法。 The proper way to cancel an existing async read/write is to close the socket. 取消现有异步读/写的正确方法是关闭套接字。

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. 如果是这样,则由于我正在实施的协议不允许我数百次打开/关闭套接字,因此我需要恢复到实际处理正常超时的命令的同步接收/发送版本。

I disagree. 我不同意。 Timeouts in protocol definitions are only advisory; 协议定义中的超时仅是建议性的; they cannot be enforced. 它们无法执行。 Or put another way, it doesn't have to be a literal Receive or Send timeout; 或者换种说法,它不必是字面上的接收或发送超时; it can be a logical "receive" or "send" timeout. 它可以是逻辑上的 “接收”或“发送”超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM