BeginReceive / BeginRead timeouts

夙愿已清 提交于 2019-12-01 15:04:59

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.

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.

Wait on ManualResetEvent with some timeout value to signal when your task is finished. If it times out before it is signaled, then you know that asynchronous operation never completed.

private ManualResetEvent receiveDone = new ManualResetEvent(false);

receiveDone.Reset();
socket.BeginReceive(...);
if(!receiveDone.WaitOne(new TimeSpan(0, 0, 0, 30))) //wait for 30 sec.
    throw new SocketException((int)SocketError.TimedOut);

Inside BeginReceive callback, use

private void ReceiveCallBack(IAsyncResult ar)
{
    /** Use ar to check if receive is correct and complete */
    receiveDone.Set();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!