Question How do I cancel a sub/function from another sub or function?


Feb 20, 2009
Saint Joseph, IL
Programming Experience
I have two command buttons on my form. One starts a complex subroutine that in turn calls numerous other subs and functions. The whole process can take quite a long amount of time. However, occasionally, the end user may kick off that process and then realize they need to cancel it and start over. So I have a second command button to kill the process, but can't get it to work, particuarly in light of the fact that there are so many possible functions/subs that could be running at a given time. (although they are all initially called by one function).

Any suggestions would be appreciated.

Dave W.


Well-known member
Apr 25, 2006
Programming Experience
Problem is, this happens:

User clicks the button
UI thread runs the click handler
Click handler code starts a massive long running op
Program becomes unresponsive because the UI thread is no longer consuming windowing messages

What you should do:

User clicks button
UI thread starts a BackgroundWorker
UI thread is free to process windowing messages
BackgroundWorker starts work
Backgroundworker has WorkerSUpportsCancellation = true
DoWork() code regularly checks the CancelPending (?) property on the BG Worker, and stops work if a cancel is pending
User clicks the Cancel button in the UI
Cancel click handler sets CancelPending = true on the BGW
Top Bottom