Главная » Просмотр файлов » Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007

Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887), страница 50

Файл №779887 Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (Symbian Books) 50 страницаWiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887) страница 502018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 50)

Override CActive’s RunL() to handle each asynchronous function’s completion event.5. Override CActive’s DoCancel() function to cancel an outstandingasynchronous function call.252ASYNCHRONOUS FUNCTIONS AND ACTIVE OBJECTS6.Override CActive’s RunError() method to handle leaves thatoccur in your RunL() event handler.7.Create your active object’s destructor, which should call the CActive::Cancel() method as part of cleanup.The next sections look at these steps in more detail.Constructing an active objectIn the constructor for your active object, you must call the base constructorCActive::CActive(TInt aPriority), passing it the active object’spriority value (see section 8.5). This is normally done in the initializationlist, as the following example shows:CMyActive::CMyActive(): CActive(CActive::EPriorityStandard){}Normally, you also create a static NewL() function for your active objectand a ConstructL() second-phase constructor function, as discussedin section 4.5.13.Adding an active object to the active schedulerIn order for the active scheduler to know about your active object asa potential source of events from the thread’s request semaphore andto distribute events to it, your active object needs to be added to thethread’s active scheduler.

This is done via a call to the static functionCActiveScheduler::Add(CActive *aAo), where aAo is a pointerto your active object. In many cases this is done in ConstructL() asfollows:CMyActive::ConstructL(){/* ... */CActiveScheduler::Add(this);}Alternatively, CActiveScheduler::Add() could be done in the activeobject constructor (since it does not leave), in a static NewL() class foryour active object, or anywhere where you can pass a pointer to youractive object. In general though, it should be in your class so that the userof the active object does not need to be concerned with adding it to theactive scheduler.INTRODUCING ACTIVE OBJECTS253Implementing requestor functionsYou typically need to implement at least one method in your activeobject that starts an asynchronous function.

When you call the asynchronous function, you pass the active object’s TRequestStatusmember, iStatus, which is inherited from the CActive base class,to the asynchronous function. After that, you call CActive’s SetActive() method to indicate that the active object has an asynchronousfunction call outstanding.As an example, if the asynchronous call associated with the activeobject is AnAsyncCall(TAny *aArg1, TRequestStatus& aStatus), then your active object’s invocation method could look as follows:void CMyCActive::InvokeAsyncFunc(TAny *aArg){/* ...

*/AnAsyncCall(aArg,iStatus);SetActive();}Implementing RunL()You override CActive’s RunL() method to handle the completion of theasynchronous function. The iStatus member (which was passed tothe asynchronous function call) can be checked in RunL() to determinethe function’s completion result. The active object can then, if desired,issue another asynchronous function request in the RunL() (from thecurrent, or another, active object).The following is an example RunL() method:void CMyActive::RunL(){if (iStatus == KErrNone){// add code to handle the event}else{// add error handling code}}Implementing a DoCancel() functionDoCancel() is a pure virtual method of CActive and you must implement this in your derived class to cancel your outstanding asynchronousrequest. DoCancel() is never called directly, but is called throughthe CActive::Cancel() method.

Cancel() only calls DoCancel()254ASYNCHRONOUS FUNCTIONS AND ACTIVE OBJECTSif your active object is waiting for its asynchronous function to complete (it calls CActive::IsActive() to check if this is the case) – sodon’t worry about your DoCancel() canceling a function that is not inprogress.Overriding the RunError() methodIf there is a possibility that the code in your RunL() function will leave,then you should always override the RunError(TInt aErr) methodto handle the error.

The aErr parameter will contain the leave code. Youshould return KErrNone once the error is handled to prevent the activescheduler from attempting to handle it. Reference section 8.4 for moredetails on active object error handling.8.3 The Active SchedulerAs described in section 8.2, the active scheduler is the event handlerfor the thread. It receives an event at the request semaphore, determines which active object it belongs to, and invokes that active object’sRunL() function.

To use active objects in a thread there must be anactive scheduler – a class of type CActiveScheduler – installed inyour thread.Often the thread you want to use active objects in will already havean active scheduler installed, and, in that case, you do not need to installyour own. GUI applications already have an active scheduler installedand running, because the GUI framework itself uses active objects toprocess GUI events. You can just add your own active objects and theywill become part of the existing pool of active objects, without needingto call any of the CActiveScheduler API methods described in thenext section.8.3.1 Installing and Starting an Active SchedulerAn active scheduler will need to be created, installed, and started forthreads that you create yourself, if you want to use active objects inthem.

This applies to threads created directly by RThread or as a resultof creating your own EXE, which has no active scheduler installed bydefault if it does not use the application framework.Setting up an active scheduler is straightforward, as shown in thefollowing example:CActiveScheduler *mySched=new (ELeave) CActiveScheduler;// install itCActiveScheduler::Install(mySched);// Add at least one active object here and invoke a requestCActiveScheduler::Start();THE ACTIVE SCHEDULER255First you create the scheduler object itself, of type CActiveScheduler.Then you call the static CActiveScheduler::Install() functionto install your scheduler as the active scheduler of the thread – makingit responsible for waiting on, and distributing events from, the thread’srequest semaphore.

If the thread already has an active scheduler installed,then a panic is raised (E32USER-CBase 43).Although your active scheduler is now installed, it does not beginprocessing events until you call CActiveScheduler::Start(). Onceyou call CActiveScheduler::Start(), the scheduler is in its eventloop – waiting at the request semaphore, invoking the appropriate activeobject’s RunL() when an event is received, and then waiting for the nextevent.So CActiveScheduler::Start() will, in effect, block your threadat the point it was called, and all code execution will now occur insidethe RunL() functions of the active objects, since everything is now executing in response to events.

CActiveScheduler::Start() returnsonly after you stop the scheduler using CActiveScheduler::Stop()(which will have to be called in an active object’s RunL() method).Once the scheduler’s stop method is called, the event loop is exited,and code execution will resume immediately after the CActiveScheduler::Start() function (usually to clean up and exit the thread).So, before you start the scheduler and enter the event-handling loop,you need to have at least one active object added to the scheduler, andhave an outstanding asynchronous function active.

If you don’t, whenyou call CActiveScheduler::Start(), you will be stuck for ever,waiting for an event that will never occur!8.3.2 Background InformationThere will be times when you’ll find it useful to understand the details ofhow the active scheduler works, in order to really understand how yourprogram behaves when using active objects. Let’s look at the event loopimplemented in CActiveScheduler::Start() in more detail.The first thing CActiveScheduler::Start() does is to block atthe thread’s request semaphore. When a signal is received on the requestsemaphore, it unblocks and determines which active object the signalbelongs to.

It does this by looking for an active object that has both itsiActive variable (the TBool member of the CActive base class thatis set when you call SetActive()) set to ETrue and its iStatus setto some value other than KRequestPending.Once an active object that meets this condition is found, the activescheduler invokes that active object’s RunL() method, after which itgoes back to waiting for the next signal at the request semaphore.This event loop repeats until the CActiveScheduler::Stop() function is invoked (in some active object’s RunL() function), at which256ASYNCHRONOUS FUNCTIONS AND ACTIVE OBJECTStime the event loop is exited and CActiveScheduler::Start()returns.Pseudo-code for the active scheduler event loop (CActiveScheduler::Start()) is shown here:do{WaitForAnyRequest();// block at the thread’s request semaphore,// return when one is received// signal receivedfor (i=0;i<number_of_active_objects;i++){if ( active_object[i].iActive &&(active_object[i].iStatus != KRequestPending) ){active_object[i].RunL();// invoke the target// active object’s RunL()break;}}if (i==number_of_active_objects) // If it did not find an active// object signal belonged to{generate_stray_signal_panic();}} while (ActiveScheduler::Stop() not called)number of active objects represents the number of activeobjects added to the active scheduler, and active object[] represents the list of those active objects.Remember (see section 8.1) that when an asynchronous function starts,it sets the TRequestStatus argument (in the case of an active object,the iStatus member variable) to KRequestPending.

When the asynchronous function completes, it writes the completion status into theTRequestStatus value and then signals the calling thread’s requestsemaphore.As you can see from the pseudo-code, when the active scheduler getsa semaphore event, it scans through its list of active objects, and invokesthe RunL() method if an active object’s iActive is set, and iStatusis a value other than KRequestPending. If the active scheduler doesnot find an active object that meets these conditions, then a stray signalpanic occurs for the thread.The pseudo-code shown in the previous example is simplified – forexample, the event loop does not show the priority handling that takesplace when multiple active object asynchronous events occur (instead, itjust runs the first active object that is found to be ready to run), nor doesit show RunL() error handling – but it should give you a basic idea ofhow the event loop works.THE ACTIVE SCHEDULER8.3.3257CActiveScheduler MethodsMany of the methods of CActiveScheduler are static, and operateon the currently installed active scheduler for the thread (or are used toinstall the scheduler itself).The static methods of CActiveScheduler are:• void Add(CActive* aActiveObject) adds aActiveObjectto the currently installed scheduler, to register for receiving events.An active object usually adds itself to the active scheduler during itsconstruction (by invoking it as CActiveScheduler::Add(this)).•void Install(CActiveScheduler* aActiveScheduler) installs the specified CActiveScheduler object as the current thread’sactive scheduler.

A panic is generated if one is already installed.• void Replace(CActiveScheduler* aActiveScheduler) issimilar to Install(), except that if an active scheduler is alreadyinstalled, then the specified active scheduler object will be installedin place of the currently installed one (as opposed to generating apanic, as Install() would).• void Start() contains the active scheduler’s event loop. Once youcall Start() the active scheduler will continually process eventsfrom the thread’s request semaphore and invoke the appropriateactive object’s RunL() method in response to them.

Характеристики

Тип файла
PDF-файл
Размер
3,36 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6447
Авторов
на СтудИзбе
306
Средний доход
с одного платного файла
Обучение Подробнее