How to (repeatedly) read from .NET SslStream with a timeout?

前端 未结 2 406
悲&欢浪女
悲&欢浪女 2021-02-05 12:15

I just need to read up to N bytes from a SslStream but if no byte has been received before a timeout, cancel, while leaving the stream in a valid state

2条回答
  •  无人及你
    2021-02-05 12:27

    You can certainly make approach #1 work. You simply need to keep track of the Task and continue waiting without calling ReadAsync again. So, very roughly:

    private Task readTask;     // class level variable
    ...
      if (readTask == null) readTask = stream->ReadAsync(buffer, 0, buffer->Length);
      if (task->Wait(timeout_ms)) {
         try {
             count = task->Result;
             ...
         }
         finally {
             task = null;
         }
      }
    

    Needs to be fleshed-out a bit so the caller can see that the read isn't completed yet but the snippet is too small to give concrete advice.

提交回复
热议问题