c# - How to stop BackgroundWorker whose `DoWork` handler only contains one (long-running) statement? -


i have problem backgroundworker dowork handler contains 1 statement. means cannot check cancellationpending flag:

private void backgroundworker_dowork(object sender, doworkeventargs e) {     calltimeconsumerfunction(); } 

how can stop backgroundworker? there work-around?

looking @ .net 4's task parallel library (tpl), came after backgroundworker , rather well-designed, can give idea how should approach this.

cancellation in tpl built on idea of cooperative cancellation. means tasks not forcibly stopped outside; instead participate in cancellation process periodically checking whether cancellation has been requested and, if so, gracefully aborting "from inside".

i recommend follow tpl's example , implement cooperative cancellation. this comment states, inject cancellation logic calltimeconsumerfunction. example:

void calltimeconsumerfunction(func<bool> shouldcancel) {                          // ^^^^^^^^^^^^^^^^^^^^^^^                            // add this; can called find out whether abort or not     … // possibly lengthy operation     if (shouldcancel()) return;     … // possibly lengthy operation }  private void backgroundworker_dowork(object sender, doworkeventargs e) {     calltimeconsumerfunction(shouldcancel: () => backgroundworker.cancellationpending); }                         // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -