I couldn't find a better topic but here it is;

1) When user clicks a button, code starts t work,

2) When another button is clicked, it would stop doing whatever it does and start to run the second button's code,

3) Or with not user interaction, an electrical power down detected from a connected device, so our software would cancel the current event and start doing the power down procedure.

How is this design mostly applied to code? I mean "stop what you are doing" part?

If you would say events, event handlers etc. how do you bind a condition to the event? and how do you tell the program without using laddered if's to end it's process?

if (powerdown) return;
if (powerdown) return;


  • 1
    This depends highly on what your language/framework supports.
    – DVK
    Commented Dec 16, 2012 at 15:11
  • Ok, let's talk for C#/.Net Framework for example.
    – tpaksu
    Commented Dec 16, 2012 at 16:48

5 Answers 5


One approach that will yield stable code is to use a state machine. Then it is best to differentiate:

  • events
  • processes/tasks in progress
  • state of your program (i.e. idle, running a task, shutting down)

Here is a very simple, informal example (in pseudo-code):

enum States = {idle, runningTask, poweringDown, stopped}
enum events = {button1, button2, powerDown, stop}

currentState = States.idle;
currentTask = nil;

// simple state engine. make it a critical section for thread safety
synchronized processEvent(event) {
  switch(currentState) {
    case States.runningTask:
       currentState = nil;
       currentTask = nil;

  switch(event) {
    case events.button1: 
         if(currentState != States.idle) break;
         currentTask = task1.start();
         currentState = States.runningTask;
    case events.button2:
         if(currentState != States.idle) break;
         currentTask = task2.start();
         currentState = States.runningTask;
    case events.powerDown:
         if(currentState != States.idle) break;
         currentTask = powerdown.start();
         currentState = States.poweringDown;
    case events.stop:
           exception("stop received before power down");
         currentTask = nil;
         currentState = stopped;
         exception("event unknown");

// onButton1Pressed will call processEvent(events.button1)
// onButton2Pressed will call processEvent(events.button2)

// task1, task2, powerdown are assumed to implement some form of thread protocol,
//i.e. start() returns an object referencing the new thread, stop() kills the thread  
  • Threading is the most common option here then. I assume task is another way to describe a threaded process.
    – tpaksu
    Commented Dec 20, 2012 at 6:53
  • @tpaksu yes, I used task synonymous for thread. The state machine approach is independent of tasks/threads though.
    – miraculixx
    Commented Dec 20, 2012 at 17:32
  • All answers use threads to apply this scenario. I wonder if there's something else. I'll wait some more before I accept a correct answer. I hope you all will understand.
    – tpaksu
    Commented Dec 21, 2012 at 6:59
  • @tpaksu: The reason that all answers use threads in the scenario is because it is required. In your scenario, a button can't be clicked while another operation is occurring in a single threaded environment because that operation would be blocking. Commented Dec 21, 2012 at 16:57
  • @SnOrfus, strictly speaking, threads are not needed, see my answer below, programmers.stackexchange.com/a/180269/70298
    – miraculixx
    Commented Dec 28, 2012 at 19:23

If you consider a multi-thread program, it should be possible to implement some control for each thread and its respective operation.

Regarding the "stop what you are doing" part: If you are consuming a resource (connection to a DB, file, etc.) and you stop manipulating its data abruptly you gotta make sure your application is reliable, you must use a .NET transaction API to make the operation atomic and control the operation queue in case the process stops, otherwise you will end up with corrupted data and your application will become inconsistent. http://www.springframework.net/doc-latest/reference/html/transaction.html

Remember: It's not a good practice to rely on Exceptions for flow-control so, connect a monitoring component to your application and take action whenever you identify that the connected server (as you mentioned in your question) is down. e.g., http://www.dofactory.com/Patterns/PatternObserver.aspx

  • Yes, running seperate threads is an answer in this situation, but not always. What if multithreading is not an option, how would someone return to idle state from a multi layered stack? I mean a calls b, then b calls c, how would someone exit directly from c to idle state?
    – tpaksu
    Commented Dec 19, 2012 at 20:14
  • Thanks for the dofactory link, it will be a good source for me, and observer/state design patterns fit for this situation while they are not really different from repeated flag checks on implementation. And of course there must be a rollback code when going back to idle.
    – tpaksu
    Commented Dec 21, 2012 at 13:09

F# (another .NET language) has an asynchronous workflow which takes care of flow and cancellation for you behind the scenes, giving you a nice, easy way to code your tasks.

Assuming you have your tasks broken down into smaller operations (that return an async themselves -- you may have to wrap them) you could do something like:

let button1Task arg =
    async {
        let! r1 = someAsyncComputation(arg)
        do! Async.Sleep(500)
        let! r2 = someOtherAsyncComputation(r1)
        return r2

Then start the operation like this:

let asy = button1Task someValue
let cts = new CancellationTokenSource()
Async.Start(asy, cts.Token)

Then, when you want to stop it, you do:


and it'll stop (I believe after finishing whatever operation it was performing -- i.e. when it hits the next do! or let!). I don't think the Cancel() call is blocking, but there may be a different version or a way to check and ensure that the computation has stopped.

In your button scenario, you could have each button or power event check for currently running tasks and cancel them before starting its own task.

The difference between this and threads is that you wouldn't have to do your ladder if's and could still safely abort the task (without having to resort to Thread.Abort()).

You might be able to find something similar for C#, but it probably won't code up as nice.

Here is some reading:

I'm still learning about these myself so this might not have been the best explanation.

  • Interesting. Ok, I don't know much about async processes, but does it run on the same thread? is it blocking other code? I mean, does the stack wait for the line to finish to execute further?
    – tpaksu
    Commented Dec 21, 2012 at 14:59
  • The Async.Start() call is asynchronous, so it spools the task up in the thread pool to run and returns immediately. There are other versions, e.g. StartImmediate, which block or start the task on the same thread (see the reference link for more). The articles I linked to should be a good read for more detials on how to use this stuff and how it works; the third explains how the async stuff is structured behind the scenes. They also talk about some stuff which might be available in C# come .NET 5
    – paul
    Commented Dec 21, 2012 at 15:26
  • I found out that java has a nearly same approach too. Thread.Start() creates a new thread and runs the code there, Thread.Run() just executes that code async in the same thread (stackoverflow.com/questions/3027495/…). I wonder why C# doesn't support that.
    – tpaksu
    Commented Dec 21, 2012 at 16:26
  • @tpaksu You can kind of do the same thing using Delegates: if you call a Delegate directly, it'll run the code in the thread you were operating in; if you call the BeginInvoke method of the Delegate, it'll run that code in a separate thread. (Note: apparently it's tough to cancel a Delegate's asynchronous run. Also note you should call EndInvoke after you get a notification that the Delegate finished running.)
    – paul
    Commented Dec 21, 2012 at 18:15

If you are targeting multithreaded scenario, you can use Tasks (.NET 4.0), or BackgroundWorker(.NET 2.0) that has support for cooperative cancellation.

Of course it requires some handling in the application logic also. This handling is limited to checking cancellation flag, and do cleanup (and return) in case of cancellation.

Supporting cancellation (without signals from other threads like Tasks, BackgroundWorker), is limited to handling error conditions, and doing cleanup/interrupt.


An alternative to threads is using an event (interrupt) mechanism coupled with a a "main loop" that runs the button and power down code, and a timer interval as the "scheduler" to figure out which piece of code to run next. In this case there are three types of events that you need to deal with:

  • button1 or button2 pressed
  • power down signal
  • timer signal, in an interval of say every 500ms

The idea is as follows:

  1. each time a button gets pressed, remember which button this was
  2. each time the timer fires, check which piece of the (button) event code is supposed to run next
  3. run the event code as part of the main loop
  4. split the event code in multiple pieces, after each piece check if the power down signal has occurred. If so, exit.

In the timer handler, check which part of the event code is supposed to run next, according to whatever button was figured in step 1. This is the "scheduler". In case of the power down signal, remember not to run any further button code, and in the main loop, run the power down code instead.

The main loop does exactly as it's name suggests:

    interrupted = false; // assigned true on alternative button pressed
    stopped = false; // assigned true at the end of power down 
    while(!stopped) {   
       while(!interrupted) {
         run the code (piece of event code) determined by the scheduler

EDIT: explaining the example in more detail:

Wait, that's just the same as the OP example, but more complicated!? No. Here the event handling, scheduling and execution are factored out and do not pollute the "buttons' code". Rather, the button code is kept simple and does not "know" of any partitions, nor does it need to provide for "cancellation" logic. Note that splitting the event code means that each piece is essentially a simple, seperate method whose execution is triggered from the main loop. There are no "if-ladders" as by OP's example. This keeps the actual logic readable and maintainable.

What if the event code is supposed to run only once? The scheduler can also be extended to allow the event code, or some parts of it, to run only once. For this introduce a data structure that keeps track of which piece has run. Every time the scheduler runs, it updates the data structure and depending on the conditions you set for each piece of code, decides whether it should be scheduled or execution.

Why not run the button code directly in each event handler? You could also run the button code directly in step 1, but this would make the UI sluggish, as it wouldn't respond until the code has finished to run. This is why the the timer handler needs to implement a scheduler. It determines which code to run. The actual code only gets to run on the main loop.

Why not run button code within the timer handler? You could also run the buttons' code directly within the timer handler. The downside is that you'd have to ensure the code does not overrun the length of the timer interval to avoid interrupt overflows, or worse.

Isn't this too complex? This design may seem overly complicated at first, but it makes sure the system continues to run smoothly by separating UI, scheduling and actual code running. The alternative, of course, is to use threads, but then the whole point of this answer is to show a solution withouth threads.

Are there improvements, e.g. for real time constraints? Essentially, this all boils down to a scheduling problem. See Scheduling Algorithms (Wikipedia) for more sophisticated approaches, e.g. to deal with real time requirements.

  • You would also need to use a event run flag to run events once. The real problem is that you let the process to complete while the power down, but it won't complete and cause you errors in some cases. The main reason I asked this to stop where the interrupt occurs no matter what, and if necessary run a rollback procedure, and then return to idle state.
    – tpaksu
    Commented Dec 21, 2012 at 9:56
  • @tpasku, if you want the interrupt (did you mean: power down?) to stop whatever the system is doing, immediately, you would have to check for the interrupt after every statement. But that would involve a lot of overhead that is unnecessary most of the time. Better to check interrupts at specific locations in your code (i.e. wherever it is in a safe state), and only then start the power down process. Please clarify your requirements if the answer is not precise enough.
    – miraculixx
    Commented Dec 21, 2012 at 11:51
  • Yes, I mentioned that in my questions bottom part as pseudocode as you can see. I'm looking for alternative patterns. And the question is clear enough as you can see by reading other answers.
    – tpaksu
    Commented Dec 21, 2012 at 12:03
  • @tpasku, adjusted the answer to reflect your original question. Hope this helps.
    – miraculixx
    Commented Dec 21, 2012 at 12:17
  • if you do the 4. action you mentioned, there is no need for scheduling, using timers or loops. That's what I've mentioned in the question and looking for some different approaches.
    – tpaksu
    Commented Dec 21, 2012 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.