c# - Canceling a task -
i have task need cancel if wait time over. instance
var t = task.factory.startnew(() => { thread.sleep(5000) // long running task "do something" }); task.waitall(new[] {t}, 1000); but seems task still keeps working. tried using cancellationtokensource didnt seem work well.
i confirmed using following snippet
static void main(string[] args) { var cancellationtokensource = new cancellationtokensource(); var t = task.factory.startnew(() => { thread.sleep(5000); console.writeline("still working"); }, cancellationtokensource.token); task.waitall(new[] {t}, 1000); cancellationtokensource.cancel(); console.readline(); } console displays "still working". thought task have been cancelled.
i sure missing something. missing? thanks.
cancellation tokens don't magically cancel anything. allow check cancellation in standardized way, e.g. via throwifcancellationrequested.
so typically you'd have task needs perform lot of work. periodically calls throwifcancellationrequested, , code needs cancel task call cancel on cancellationtokensource when needs to. task throw when next checks cancellation, , well.
it sounds you're looking non-cooperative cancellation - , dangerous, same reasons normal thread.abort dangerous. it's cleaner let task pick points @ allow cancelled.
Comments
Post a Comment