How to stop execution of a particular set of code

Hi all,

I am writing a windows form application program that on the click of a button starts to execute a bunch of code. This code takes about a minute to execute.

I want to add a button to that form that allows me to stop the code from executing, say 30 seconds into the code. What command will allow me to do that?

If I use exit(0); this ends the program and exits out. I am looking for something that will end the execution of a different "button-press" and yet leave my windows form running.

Thank you.
Last edited on
There are two ways you could do it.

The simplest way would be to have a variable that the long code would check:

bool calculationHasBeenHalted = false;

void OnLongCodeButtonClick ()
      // ...
      if (calculationHasBeenHalted) return;
      // ...
      if (calculationHasBeenHalted) return;
      // etc.

void OnHaltButtonClick ()
      calculationHasBeenHalted = true;

Implementation of this may vary depending on your calculation.

An alternative, which may be more desirable since it will immediately halt processing, would be to use multithreading. I won't try to explain it since there are plenty of articles on the net that do a better job than I could, but the gist of it would be that you would launch a thread that does the processing by using LaunchThread(...) (assuming you're using Windows; if you're not, the process will still generally be the same). When the user presses the Stop button, you would call TerminateThread(...) to immediately stop the processing. Note that this may leave various data structures in an invalid state, depending on what sort of processing your thread is doing.

The first method is less accurate, but is safer and easier to implement. The second will cause the processing to stop immediately, but is more difficult to implement in a bug-free way.
Last edited on
Topic archived. No new replies allowed.