Главная » Просмотр файлов » Symbian OS Explained - Effective C++ Programming For Smartphones (2005)

Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885), страница 30

Файл №779885 Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (Symbian Books) 30 страницаSymbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885) страница 302018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

The priority generally defaults to EPriorityStandard (=0, from class CActive) or EActivePriorityDefault (=0if using the TActivePriority enumeration defined in coemain.hfor use with application code). This is the standard priority for anactive object and should be used unless there is a good reason to setits priority to some other value, for example to EActivePriorityWsEvents (=100) for handling user input responsively.• An active object provides at least one method for clients to initiaterequests to its encapsulated asynchronous service provider.

The activeobject always passes its own iStatus object to the asynchronousfunction, so does not need to include a TRequestStatus referenceamong the parameters to the request issuer method unless it is actingas a secondary provider of asynchronous services.• After submitting a request to an asynchronous service provider, theactive object must call SetActive() upon itself. This sets theiActive flag, which indicates an outstanding request. This flag isused by the active scheduler upon receipt of an event and by the baseclass upon destruction, to determine whether the active object can beremoved from the active scheduler.• An active object should only submit one asynchronous request at atime. The active scheduler has no way of managing event-handlingfor multiple requests associated with one active object.• An active object should pass its iStatus object to an asynchronousservice function.

It should not reuse that object until the asynchronousfunction has completed and been handled. The active schedulerinspects the TRequestStatus of each active object to determineits completion state and the event-handling code uses the value itcontains to ascertain the completion result of the function.• An active object must implement the pure virtual methods RunL()and DoCancel() declared in the CActive base class. Neithermethod should perform lengthy or complex processing, to avoidholding up event handling in the entire thread.

This is particularlyimportant in GUI applications where all user interface code runs inthe same thread. If any single RunL() is particularly lengthy, the userinterface will be unresponsive to input and will ”freeze” until thatevent handler has completed.RESPONSIBILITIES OF AN ASYNCHRONOUS SERVICE PROVIDER133• An active object must ensure that it is not awaiting completion ofa pending request when it is about to be destroyed. As destructionremoves it from the active scheduler, later completion will generatean event for which there is no associated active object. To preventthis, Cancel() should be called in the destructor of an activeobject.

The destructor of the CActive base class checks that thereis no outstanding request before removing the object from the activescheduler and raises an E32USER – CBASE 40 panic if there is, tohighlight the programming error. The base class destructor cannotcall Cancel() itself because that method calls the derived classimplementation of DoCancel() – and, of course, C++ dictates thatthe derived class has already been destroyed by the time the baseclass destructor is called.• Objects passed to the asynchronous service provider by the issuermethods must have a lifetime at least equal to the time taken tocomplete the request. This makes sense when you consider that theprovider may use those objects until it is ready to complete therequest, say if it is retrieving and writing data to a supplied buffer.This requirement means that parameters supplied to the providershould usually be allocated on the heap (very rarely, they may beon a stack frame that exists for the lifetime of the entire program).In general, parameters passed to the asynchronous service providershould belong to the active object, which is guaranteed to exist whilethe request is outstanding.• If a leave can occur in RunL(), the class should override the defaultimplementation of the virtual RunError() method to handle it.RunError() was added to CActive in Symbian OS v6.0 to handle any leaves that occur in the RunL() event handler.

If a leaveoccurs, the active scheduler calls the RunError() method of theactive object, passing in the leave code. RunError() should returnKErrNone to indicate that it has handled the leave, say by cleaningup or resetting the state of the active object. The default implementation, CActive::RunError(), does not handle leaves and indicatesthis by simply returning the leave code passed in.9.3 Responsibilities of an Asynchronous Service ProviderAn asynchronous service provider has the following responsibilities:• Before beginning to process each request, the provider must setthe incoming TRequestStatus value to KRequestPending toindicate to the active scheduler that a request is ongoing.134ACTIVE OBJECTS UNDER THE HOOD• When the request is complete, the provider must set the TRequestStatus value to a result code other than KRequestPendingby calling the appropriate RequestComplete() method from theRThread or User class.• The asynchronous service provider must only call RequestComplete() once for each request.

This method generates an eventin the requesting thread to notify it of completion. Multiple completion events on a single active object result in a stray signal panic.Completion may occur normally, because of an error condition orbecause the client has cancelled an outstanding request. If the clientcalls Cancel() on a request after it has completed, the asynchronousservice provider must not complete it again and should simply ignorethe cancellation request. This is discussed further in Sections 9.8and 9.9.• The provider must supply a corresponding cancellation method foreach asynchronous request; this should complete an outstandingrequest immediately, posting KErrCancel into the TRequestStatus object associated with the initial request.9.4 Responsibilities of the Active SchedulerThe active scheduler has the following responsibilities:• Suspending the thread by a call to User::WaitForAnyRequest().When an event is generated, it resumes the thread and inspects thelist of active objects to determine which has issued the request thathas completed and should be handled.• Ensuring that each request is handled only once.

The active schedulershould reset the iActive flag of an active object before calling itshandler method. This allows the active object to issue a new requestfrom its RunL() event handler, which results in SetActive() beingcalled (which would panic if the active object was still marked activefrom the previous request).• Placing a TRAP harness around RunL() calls to catch any leavesoccurring in the event-handling code.

If the RunL() call leaves,the active scheduler calls RunError() on the active object initially. If the leave is not handled there, it passes the leave code toCActiveScheduler::Error(), described in more detail shortly.• Raising a panic (E32USER – CBASE 46) if it receives a ”stray signal”.This occurs when the request semaphore has been notified of anevent, but the active scheduler cannot find a ”suitable” active objectNESTING THE ACTIVE SCHEDULER135(with iActive set to ETrue and a TRequestStatus indicatingthat it has completed).9.5 Starting the Active SchedulerOnce an active scheduler has been created and installed, its eventprocessing wait loop is started by a call to the static CActiveScheduler::Start() method. Application programmers do not haveto worry about this, since the CONE framework takes care of managingthe active scheduler.

If you are writing server code, or a simple consoleapplication, you have to create and start the active scheduler for yourserver thread, which can be as simple as follows:CActiveScheduler* scheduler = new(ELeave) CActiveScheduler;CleanupStack::PushL(scheduler);CActiveScheduler::Install(scheduler);The call to Start() enters the event processing loop and doesnot return until a corresponding call is made to CActiveScheduler::Stop().

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

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

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

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