Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 471
Smith5727 Avatar asked Mar 01 '26 12:03

Smith5727


1 Answers

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);
like image 104
Guru Stron Avatar answered Mar 03 '26 04:03

Guru Stron