How to cancel NetworkStream.ReadAsync without closing stream

后端 未结 3 1669
陌清茗
陌清茗 2020-12-17 15:52

I am trying to use NetworkStream.ReadAsync() to read data but I cannot find how to cancel the ReadAsync() once called. For background, the NetworkStream is provided to me b

3条回答
  •  不知归路
    2020-12-17 16:21

    You can implement an async wrapper around NetworkStream.Read (or ReadAsync), which also receives a cancellationtoken that you can monitor and honor yourself. Something like this:

    Task MyCancelableNetworkStreamReadAsync(NetworkStream stream, CancellationToken ct)
    {
    ...
    if(this.stream.CanRead)
    {
      do 
      {
        //check ct.IsCancellationRequested and act as needed
        bytesRead = await this.stream.ReadAsync(this.buffer, 0, (int)this.buffer.Length);
      }
      while(myNetworkStream.DataAvailable);
    }
    

    Please note that I am only trying to illustrate the idea and you might wnt to consider returning Task, as well as whether to have the do{}while loop, any additional processing or cleanup, etc. - all according to your needs.

    I would also point your attention to the article by Stephen Toub How do I cancel non-cancelable async operations? and the WithCancellation extension he creates there.

提交回复
热议问题