BeginReceive /超时的BeginRead [英] BeginReceive / BeginRead timeouts

查看:1105
本文介绍了BeginReceive /超时的BeginRead的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的NetworkStream&安培; TcpClient的使用异步的BeginRead接收数据。我需要一个超时适用于该操作,以使得在指定的时间量之后的读将被中止。

I'm using a NetworkStream & TcpClient to asynchronously receive data using BeginRead. I need to apply a time-out to this operation, such that after a specified amount of time the read will be aborted.

至于我能告诉,这是不支持的NetworkStream或TcpClient的 - 有一个ReceiveTimeout属性,但是这似乎只适用于同步等价 - 读

As far as I'm able to tell, this isn't supported on NetworkStream or TcpClient - there is a ReceiveTimeout property, but this appears to only apply to the synchronous equivalent - 'Read'.

即使底层Socket类似乎并不支持超时在BeginReceive方法。

Even the underlying Socket class doesn't appear to support timeouts in its BeginReceive method.

我搜索关于这个问题,唯一的建议的解决我所看到的是另外搭建后台线程取消操作,如果它不超时时间内完成。这似乎是一个可怕的黑客。当然还有更好的办法?

I've searched on this issue and the only suggested resolution I've seen is to set up another background thread to cancel the operation if it doesn't complete within the timeout period. This seems like a horrible hack. Surely there is a better way?

推荐答案

这是做到这一点的唯一方法,因为当你使用异​​步操作,发起操作的线程处于关闭状态做别的事情。因为执行线程被阻塞,直到读操作完成的超时功能可与同步版本。

It's the only way to do it, because when you're using an asynchronous operation, the thread that initiated the operation is off doing something else. The timeout is available with the synchronous version because the execution thread is blocked until the Read operation completes.

如果你将不得不使用一个后台线程取消操作,虽然不会有太多点继续使用异步开始/结束的方法。如果你打算分拆后台线程,刚刚从后台线程执行同步读取操作,然后可以使用ReceiveTimeout。

If you would have to use a background thread to cancel the operation, though, there wouldn't be much point to continuing to use the asynchronous Begin/End methods. If you're going to spin off a background thread, just perform a synchronous Read operation from the background thread, and then you can use the ReceiveTimeout.

这篇关于BeginReceive /超时的BeginRead的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆