Search code examples
c#asynchronous.net-standard.net-7.0cancellation-token

TryReset CancellationSource .NET Standard


We're "downgrading" a net7.0 project to netstandard2.0. Most of the code seems to be good but we get an error on that it cannot find the TryReset method.

 cancellationTokenSource.TryReset(); <-- TryReset method cannot be found
 cancellationTokenSource.CancelAfter(10000);

What would the netstandard2.0 equivalent to TryReset be?


Solution

  • Based on the implementation there is no "direct" equivalent since managing internal state is involved. You can use conditional compilation to leverage the method for cases when the library is used with .NET6 + (when it was introduced):

    #if NET6_0_OR_GREATER
    cancellationTokenSource.TryReset();
    // ...
    #else
    cancellationTokenSource.Dispose();
    cancellationTokenSource = new CancellationTokenSource();
    #endif
    
    cancellationTokenSource.CancelAfter(10000);