Class CancellationGuard
Ensures that a block of code running on a background thread cleanly exits before a System.Threading.CancellationTokenSource.Cancel() call completes.
[MustDisposeResource]
public class CancellationGuard
- Inheritance
-
objectCancellationGuard
- Extension Methods
Examples
This class is best used in a using-block:
using (new CancellationGuard(cancellationToken))
{
// Your code
}
Remarks
Do not use this if System.Threading.CancellationTokenSource.Cancel() is called from the same System.Threading.SynchronizationContext the guarded code is running under. This could lead to deadlocks.
Constructors
CancellationGuard(CancellationToken)
Registers a callback for the cancellationToken
that blocks calls to System.Threading.CancellationTokenSource.Cancel() until Dispose() has been called.
public CancellationGuard(CancellationToken cancellationToken)
Parameters
cancellationToken
CancellationTokenUsed to signal cancellation requests.
CancellationGuard(CancellationToken, TimeSpan)
Registers a callback for the cancellationToken
that blocks calls to System.Threading.CancellationTokenSource.Cancel() until Dispose() has been called.
public CancellationGuard(CancellationToken cancellationToken, TimeSpan timeout)
Parameters
cancellationToken
CancellationTokenUsed to signal cancellation requests.
timeout
TimeSpanA timespan after which the cancellation will be considered completed even if Dispose() has not been called yet.
Methods
Dispose()
Releases the block and allows System.Threading.CancellationTokenSource.Cancel() to complete.
public void Dispose()