Is there a clean way to check the cancel request in BackgroundWorker without re-entering the same code over and over?

If I want to periodically check if there is a revocation request, I would constantly use the following code below inside my DoWork event handler:

if(w.CancellationPending == true) { e.Cancel = true; return; } 

Is there a clean way to test the cancellation request in BackgroundWorker in C # without re-entering the same code again and again?

Please see the following code below:

 void worker_DoWork(object sender, DoWorkEventArgs e) { ... BackgroundWorker w = sender as BackgroundWorker; if(w.CancellationPending == true) { e.Cancel = true; return; } some_time_consuming_task... if(w.CancellationPending == true) { e.Cancel = true; return; } another_time_consuming_task... if(w.CancellationPending == true) { e.Cancel = true; return; } ... } 
+5
source share
1 answer

Use while loop and delegates

Add your task to the delegate list, then check your condition in a loop.

You can use the special Action delegate to facilitate this task (see http://msdn.microsoft.com/en-us/library/system.action(v=vs.110).aspx )

 void worker_DoWork(object sender, DoWorkEventArgs e) { List<Action> delegates = new List<Action>(); delegates.add(some_time_consuming_task); delegates.add(another_time_consuming_task); BackgroundWorker w = sender as BackgroundWorker; while(!w.CancellationPending && delegate.Count!=0) { delegates[0](); delegates.remove(0); } if(w.CancellationPending) e.Cancel = true; } 
+5
source

Source: https://habr.com/ru/post/1205774/


All Articles