Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 818
LBushkin Avatar asked Jul 14 '11 21:07

LBushkin


1 Answers

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;
        }
    }
}
like image 118
Jin-Wook Chung Avatar answered Oct 23 '22 11:10

Jin-Wook Chung