LBushkin
LBushkin

Reputation: 131796

Proper way to use LINQ with CancellationToken

I am trying to write a LINQ query that would support cancellation using the CancellationToken mechanism that is provided in the .NET framework. However, it's unclear what the proper way to combine cancellation and LINQ would be.

With PLINQ, it's possible to write:

 var resultSequence = sourceSequence.AsParallel()
                                    .WithCancellation(cancellationToken)
                                    .Select(myExpensiveProjectionFunction)
                                    .ToList();

Unfortunately, WithCancellation() only applies to a ParallelEnumerable - so it can't be used with a plain old LINQ query. It's possible, of course, to use WithDegreeOfParallelism(1) to turn a parallel query into a sequential one - but this is clearly a hack:

 var resultSequence = sourceSequence.AsParallel()
                                    .WithDegreeOfParallelism(1)
                                    .WithCancellation(cancellationToken)
                                    .Select(myExpensiveProjectionFunction)
                                    .ToList();

I would also like to avoid creating a separate Task for this operation, as I need to do this in several places, and I need to be able to control which thread this code runs on in some instances.

So, short of writing my own implementation of WithCancellation() - is there an alternative that would achieve the same thing?

Upvotes: 11

Views: 6547

Answers (1)

Jin-Wook Chung
Jin-Wook Chung

Reputation: 4344

How about this approach?

var resultSequence = sourceSequence.WithCancellation(cancellationToken)
                        .Select(myExpensiveProjectionFunction)
                        .ToList();

static class CancelExtention
{
    public static IEnumerable<T> WithCancellation<T>(this IEnumerable<T> en, CancellationToken token)
    {
        foreach (var item in en)
        {
            token.ThrowIfCancellationRequested();
            yield return item;
        }
    }
}

Upvotes: 37

Related Questions