c# - How to abort or terminate a task of TPL when cancellation token is unreachable? -
let's consider method:
task foo(ienumerable items, cancellationtoken token) { return task.run(() => { foreach (var in items) token.throwifcancellationrequested(); }, token); }
then have consumer:
var cts = new cancellationtokensource(); var task = foo(items, cts.token); task.wait();
and example of items:
ienumerable items { { yield return 0; task.delay(timeout.infinitetimespan).wait(); yield return 1; } }
what task.wait? i cannot put cancel token collection of items.
how kill not responding task or around this?
i found 1 solution allows put cancellation token items originating thid parties:
public static ienumerable<t> tocancellable<t>(this ienumerable<t> @this, cancellationtoken token) { var enumerator = @this.getenumerator(); (; ; ) { var task = task.run(() => enumerator.movenext(), token); task.wait(token); if (!task.result) yield break; yield return enumerator.current; } }
now need use:
items.tocancellable(cts.token)
and not hang after cancel request.
Comments
Post a Comment