public ThrowIfCancellationRequested ( ) : void | ||
return | void |
public void DoSomeWork(CancellationToken cancellationToken) { for(int i = 0; i < 1000000; i++) { cancellationToken.ThrowIfCancellationRequested(); // do some work... } }In this example, we have a method that is doing some work in a loop. The CancellationToken.ThrowIfCancellationRequested method is called at the beginning of each loop to check if a cancellation request has been made. If a cancellation request has been made, then an OperationCanceledException will be thrown, and the method will exit. This method can be used to gracefully stop long-running operations when a cancellation request is made, and prevent them from continuing to consume resources unnecessarily. This method is part of the System.Threading namespace in the .NET Framework, and is typically used in conjunction with the System.Threading.CancellationTokenSource class.