Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to make some kind of "aggregated" CancelationTokenSource in c#?

Tags:

c#

Is there any way to implement CancelationTokenSource, which allow to aggregate two or more others CancelationToken inside? which allows me to write something like this:

void async Task DoSomeWorkAsync(CancelationToken Token)
{
    var cts = AggregatedCancelationTokenSource(Token, 
      new CancelationTokenSource(TimeSpan.FromSeconds(30)).Token);
    //Cancelation occurred:
    // when timeout will be expired 
    //  or 
    // when external Token.IsCancellationRequested will start to return "true"
    await DoSomeOtherWorkAsync(cts.Token);
}
like image 439
Dmitriy.Nemykin Avatar asked Jan 18 '26 10:01

Dmitriy.Nemykin


1 Answers

Yes, you can use CancellationTokenSource.CreateLinkedTokenSource, from documentation:

Creates a CancellationTokenSource that will be in the canceled state when any of the source tokens are in the canceled state.

like image 125
b2zw2a Avatar answered Jan 19 '26 22:01

b2zw2a



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!