Can i cancel StreamReader.ReadLineAsync with a CancellationToken?

前端 未结 4 1531
北荒
北荒 2020-12-16 12:02

When I cancel my async method with the following content by calling the Cancel() method of my CancellationTokenSource, it will stop eventually. How

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 12:38

    I generalized this answer to this:

    public static async Task WithCancellation(this Task task, CancellationToken cancellationToken, Action action, bool useSynchronizationContext = true)
    {
        using (cancellationToken.Register(action, useSynchronizationContext))
        {
            try
            {
                return await task;
            }
            catch (Exception ex)
            {
    
                if (cancellationToken.IsCancellationRequested)
                {
                    // the Exception will be available as Exception.InnerException
                    throw new OperationCanceledException(ex.Message, ex, cancellationToken);
                }
    
                // cancellation hasn't been requested, rethrow the original Exception
                throw;
            }
        }
    }
    

    Now you can use your cancellation token on any cancelable async method. For example WebRequest.GetResponseAsync:

    var request = (HttpWebRequest)WebRequest.Create(url);
    
    using (var response = await request.GetResponseAsync())
    {
        . . .
    }
    

    will become:

    var request = (HttpWebRequest)WebRequest.Create(url);
    
    using (WebResponse response = await request.GetResponseAsync().WithCancellation(CancellationToken.None, request.Abort, true))
    {
        . . .
    }
    

    See example http://pastebin.com/KauKE0rW

提交回复
热议问题