BeginReceive / BeginRead timeouts

后端 未结 2 1266
遥遥无期
遥遥无期 2021-01-17 09:46

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 o

2条回答
  •  遇见更好的自我
    2021-01-17 10:21

    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();
    }
    

提交回复
热议问题