design for interruptable operations

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?

method1();
if (powerdown) return;
method2(); 
if (powerdown) return;

etc.

2

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:
       currentTask.stop();
       currentState = nil;
       currentTask = nil;
       break;
    default: 
   }

  switch(event) {
    case events.button1: 
         if(currentState != States.idle) break;
         currentTask = task1.start();
         currentState = States.runningTask;
         break;
    case events.button2:
         if(currentState != States.idle) break;
         currentTask = task2.start();
         currentState = States.runningTask;
         break;
    case events.powerDown:
         if(currentState != States.idle) break;
         currentTask = powerdown.start();
         currentState = States.poweringDown;
         break;
    case events.stop:
         if(!powerdown.finished())
           exception("stop received before power down");
         currentTask = nil;
         currentState = stopped;
         break;
    default: 
         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  

5

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

2

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:

cts.Cancel()

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:

  • Articles
    • http://tomasp.net/blog/csharp-fsharp-async-intro.aspx
    • http://tomasp.net/articles/async-csharp-differences.aspx
    • http://tomasp.net/blog/async-compilation-internals.aspx
  • Reference
    • http://msdn.microsoft.com/en-us/library/ee370232.aspx

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

4

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.

6

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật