We can cancel a PLINQ query using the CancellationTokenSource and CancellationToken classes. The cancellation token is passed to the PLINQ query using the WithCancellation clause and then we can call CancellationToken.Cancel to cancel the query operation. When a query is canceled, it throws OperationCancelledException.
This is done as follows:
- Create a cancellation token source:
CancellationTokenSource cs = new CancellationTokenSource();
Create a task that starts immediately and cancel the token after 4 seconds
Task cancellationTask = Task.Factory.StartNew(() =>
{
Thread.Sleep(4000);
cs.Cancel();
});
- Wrap the PLINQ query inside a try block:
try
{
var result = range.AsParallel()
.WithCancellation(cs.Token)
.Select(number => number)
.ToList...