开发者

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 al开发者_StackOverflow中文版so 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?


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;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜