In the previous section we already know how to create and use active objects, and you have a certain understanding of the creation and use of active objects. In this section I will delve into the activities of the object mechanism, divided into "active object Workflow", "Signal lost error" two parts, for everyone to analyze the working principle of the active object.
I. Workflow of the active object
First we use a timeline diagram to illustrate the processes that are created and invoked between the application, the active object, the active scheduler, and the asynchronous function server:
Below we follow each step combining code (click here to download code) to explain:
1. Create and install the Activity Scheduler:
CActiveScheduler* scheduler = new (ELeave) CActiveScheduler();
CleanupStack::PushL(scheduler);
CActiveScheduler::Install(scheduler);
If you create an application that is based on the GUI application framework, the framework has created and installed the active scheduler for us, and we can use the Cactivescheduler series of methods directly.
2. Create the active object
iMyAO = CMyActiveObject::NewL(*console);
The Cmyactiveobject class created here is an active object that inherits from the Cactive class.
3. Add the active object to the active scheduler
void CMyActiveObject::ConstructL()
{
....
CActiveScheduler::Add( this); // Add to scheduler
}
As you can see, the active object has already added its own pointer to the active scheduler when it is created through phase two construction.
4, Startl
Startl the method that invokes an asynchronous function for an application requesting the active object, where the user can rename the method according to his or her own needs:
void CMyActiveObject::StartL(TTimeIntervalMicroSeconds32 aDelay)
{
Cancel(); // 取消异步函数请求
iStatus = KRequestPending;
iTimer.After(iStatus, aDelay); // 在此处调用异步函数
SetActive(); // 将成员变量iActive = ETrue
}
Because it is not guaranteed that the user will not recall the Startl method while waiting for the asynchronous function call to return, the Cancel () method is invoked first at the entry point of the Startl method to cancel the asynchronous request, otherwise a notorious "signal loss" error may occur.
5, istatus = krequestpending
In the above code Startl method, before an asynchronous function call, you first set the istatus to krequestpending so that the active scheduler can match over the duration.