Task.Factory.FromAsync with CancellationTokenSource

前端 未结 3 1872
挽巷
挽巷 2020-12-31 07:32

I have the following line of code used to read asynchronously from a NetworkStream:

int bytesRead = await Task.Factory.FromAsync(this.stream.Begin         


        
3条回答
  •  抹茶落季
    2020-12-31 08:12

    Gigi, unfortunately the semantic nature of FromAsync indicates that you are only adapting an asynchronous process to TPL's API (TPL = Microsoft's Task Parallel Library)

    In essence, TPL's ReadAsync controls the async behaviour itself, whilst FromAsync only wraps the behaviour (but doesn't control it).

    Now since Cancellation is a TPL specific construct, and since FromAsync has no control on the inner workings of the async method being called, then there is no guaranteed way to cleanly cancel the task and ensure that all resources are closed correctly (which is why it was omitted. If you're curious, just decompile the method ;))

    In these situations, it makes more sense to wrap the actual async call yourself in a normal task and detect the OperationCancelled exception, which will give you the opportunity to close your stream by making the appropriate calls.

    In short, the answer is no, but there is nothing stopping you from creating a generic overloaded method that will pick the correct strategy to cleanly close a stream depending on its type.

提交回复
热议问题