c# - Proper way to use LINQ with CancellationToken -
c# - Proper way to use LINQ with CancellationToken -
i trying write linq query back upwards cancellation using cancellationtoken
mechanism provided in .net framework. however, it's unclear proper way combine cancellation , linq be.
with plinq, it's possible write:
var resultsequence = sourcesequence.asparallel() .withcancellation(cancellationtoken) .select(myexpensiveprojectionfunction) .tolist();
unfortunately, withcancellation()
applies parallelenumerable
- can't used plain old linq query. it's possible, of course, utilize withdegreeofparallelism(1)
turn parallel query sequential 1 - hack:
var resultsequence = sourcesequence.asparallel() .withdegreeofparallelism(1) .withcancellation(cancellationtoken) .select(myexpensiveprojectionfunction) .tolist();
i avoid creating separate task
operation, need in several places, , need able command thread code runs on in instances.
so, short of writing own implementation of withcancellation()
- there alternative accomplish same thing?
how 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 homecoming item; } } }
c# .net linq parallel-processing cancellation
Comments
Post a Comment