c# - Cancel all async tasks -
is possible cancel async methods, without knowing running?
for example have several classes may run async tasks:
class class1 { public async void sometask() { (int = 0; < 5; i++) { // doing job await task.delay(2000); } } } class class2 { public async void continuouslytask() { (;;) { // doing job on background await task.delay(1000); } } }
and want turn off every async task, before logout:
class program { static void main(string[] args) { var p = new program(); var c1 = new class1(); var c2 = new class2(); c1.sometask(); c2.continuouslytask(); while (console.readkey().key != consolekey.enter) { } p.logout(); } private void logout() { // cancel async tasks // , logout work } }
is possible this, without saving tasks query?
this extending @frankfajardo answer provide concrete example. when pass in cancellationtoken
, need monitor cancellation request outside. this:
class class1 { public async task sometaskasync(cancellationtoken cancellationtoken) { (int = 0; < 5; i++) { if (cancellationtoken.iscancellationrequested) break; // doing job await task.delay(2000); } } } class class2 { public async task continuouslytaskasync(cancellationtoken cancellationtoken) { while (!cancellationtoken.iscancellationrequested) { // doing job on background await task.delay(1000); } } }
and when want cancel it, add cancellationtokensource.cancel()
call code:
static void main(string[] args) { var p = new program(); var c1 = new class1(); var c2 = new class2(); var cancellationtokensource = new cancellationtokensource(); var sometask = c1.sometask(cancellationtokensource.token); var continuoustask = c2.continuouslytask(cancellationtokensource.token); while (console.readkey().key != consolekey.enter) { } cancellationtokensource.cancel(); task.waitall(sometask, continuoustask); p.logout(); }
note i'm using task.waitall
because console application main
can't async. otherwise, use task.whenall
returns awaitable task
.
Comments
Post a Comment