0

I have async method that takes CancellationToken as parameter so that it can be passed to another method called later. I would like to call that inner method with CancellationToken that cancels after 10s or if "parent" CancellationToken is canceled manually.

I have method A with CancellationToken parameter. I have method B with CancellationToken parameter called from method A.

I would like to call method B with token that is canceled after 10s or when "original" token that gets passed to method A gets cancelled.

I know I can use CancellationTokenSource(TimeSpan.FromSeconds(10)) to get token that canceled after 10s and pass it to method B from A. But I don't know how to cancel method B if token from method A's parameters gets canceled.

5
  • 1
    You will likely need 2 CancellationTokens for this.
    – TheGeneral
    Jul 22, 2019 at 9:03
  • 1
    In addition to @TheGeneral this might help. Jul 22, 2019 at 9:08
  • Have you tried using CancellationToken.Register on the first token to schedule the cancellation on the second one using CancellationTokenSource.CancelAfter?
    – Dirk
    Jul 22, 2019 at 9:27
  • @SebastianSchumann - That is the answer. If you create full response I'll accept it as the answer.
    – Hooch
    Jul 22, 2019 at 10:11
  • 1
    @PauloMorgado adds the same as answer. Accept his one - adding the same answer doesn't make sense Jul 22, 2019 at 13:14

1 Answer 1

2

Try this:

async Task A(CancellationToken ct)
{
    using (var timoutCts = new CancellationTokenSource(10000))
    {
        using (var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(ct, timoutCts.Token))
        {
            await B(combinedCts.Token);
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.