TryReset CancellationSource .NET Standard

52 Views Asked by At

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?

2

There are 2 best solutions below

0
Guru Stron On BEST ANSWER

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);
0
Theodor Zoulias On

The netstandard2.0 equivalent to TryReset is to discard the existing CancellationTokenSource, and instantiate a new one.