03.01.2013 Views

Chapter 1

Chapter 1

Chapter 1

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Exit();<br />

break;<br />

I just cancel the active object from here. I destroy it from its owning class's destructor – this<br />

is the right place to destroy it, since the destructor gets called in cleanup situations, while the<br />

command handler does not. Prior to coding this Cancel() explicitly in the exit command<br />

handling code, my DoCancel() was being called from the active object's destructor and<br />

was trying to draw to an environment that by then had been destroyed.<br />

You should always be careful about doing anything fancy from an active object's<br />

DoCancel(). Nothing in a DoCancel() should leave or allocate resources, and<br />

DoCancel() should complete very quickly. I got myself into trouble because I don't simply<br />

stop flashing when I cancel; instead, I restore the visibility state, which involves drawing. In<br />

fact, this is a good rule for any kind of cleanup or destructor; just cleanup and destroy – don't<br />

do anything else.<br />

17.3.2 State Machines<br />

Active objects can be used to implement state machines. As an example, say, we wish to<br />

amalgamate the CDelayedHello and CFlashingHello functionality and so produce the<br />

effect of the Hello world! message flashing on/off once followed by the info-message with the<br />

same greeting. This cycle repeats until cancelled. This behavior can be represented by the<br />

state diagram shown in Figure 17.11.<br />

Figure 17.11<br />

The state machine is initially in the Idle state and starting the machine moves it into the<br />

Show Hello state. The greeting is shown and a timer is started. When the timer completes,<br />

it notifies the state machine and it moves to the Hide Hello state – the greeting is<br />

removed. The state machine then moves itself into the Show Info Hello state. Here, an<br />

info-message is produced showing the greeting text. Again, the state machine moves itself<br />

into the Wait State in which it starts a timer. When the timer completes, it notifies the<br />

state machine and it moves to Show Hello state and the cycle repeats. Cancelling the<br />

state machine can be done in any state and simply moves the state machine into the Idle<br />

state.<br />

This is a very simple state machine but demonstrates the idea. The CMultiPartHello<br />

object implements the state machine. Essentially, it is an active object that maintains an<br />

outstanding request once it has been started until it is cancelled.<br />

class CMultiPartHello : public CActive<br />

{<br />

public:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!