Главная » Просмотр файлов » Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356

Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879), страница 28

Файл №779879 Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (Symbian Books) 28 страницаIssott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879) страница 282018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

The reason for this is thatyou will already have one error path at the point at which the requestcompletion is handled and by leaving here you only introduce anothererror path which unnecessarily complicates calling code. Instead youshould ensure that you re-use the existing error path, perhaps by callingyour request completion handling function directly.Last but not least, don’t forget to actually issue the asynchronousrequest to the asynchronous service provider, accessed through iService. Most Symbian OS APIs do this by taking a TRequestStatusobject to allow the service to pass back the request completion event.10It’s important that you use the iStatus provided by the CActive baseclass so that the completion is handled as described below in the activeobject’s RunL() function.void CMyActive::IssueAsyncRequest(){ASSERT(!IsActive());// Actually issue the requestiService->AsyncRequest(iStatus);9 This is when a request has been signaled as complete and either there is no activeobject available or an active object is found that has neither been set active nor has arequest pending.

The result is an E32USER-CBase panic.10As per Request Completion (see page 104).ACTIVE OBJECTS141// Tell the framework that a request is pending but// do it after the async request in case it LeavesSetActive();}You must implement a RunL() where you should handle completionof the asynchronous request issued by IssueAsyncRequest() asappropriate to your situation:void CMyActive::RunL(){// As an example, this Leaves if the request completed with an error so// that errors are handled in RunError()User::LeaveIfError(iStatus);// Implementation-specific, request-handling code...}It is optional to implement the RunError() method but if the RunL()may Leave and you need error-handling specific to this active object thenyou should do so and use it to resolve any errors that occurred for youroriginal request.

You should return KErrNone for errors that are handledwithin the function but return the actual error code for any errors that arenot handled.If you don’t handle an error within your active object, it’ll be passed tothe active scheduler to resolve. Exactly how this is done depends on whatplatform you’re on.11 However, it is common practice within applicationsfor your CxxxAppUi::HandleError() function to be called.

If thatdoesn’t handle the error then on UIQ a dialog is shown to the end userwhilst on S60 the application is silently terminated.TInt CMyActive::RunError(TInt aError){// For example we can resolve KErrNotFound errors here ...if (aError == KErrNotFound){// resolve error such as by retryingIssueAsyncRequest();return KErrNone; // error resolved}return aError; // error not handled}In the destructor of the active object, in addition to all the normalthings you’d do, such as clean up any resources you’ve used, you shouldalways call CActive::Cancel() to ensure that there is no outstanding11 Since device manufacturers can customize the active scheduler by deriving fromCActiveScheduler.142COOPERATIVE MULTITASKINGrequest at the point of destruction.

Failing to do so and leaving arequest outstanding will cause a stray signal when the asynchronous callcompletes and the active scheduler tries to invoke the RunL() of an objectthat no longer exists. Remember you should never call DoCancel()directly because, unlike Cancel(), this doesn’t check if there is anoutstanding request before sending a cancel to the service provider.CMyActive::∼CMyActive(){Cancel();// Other cleanup code...}You must implement the DoCancel() method to call the cancelmethod that matches the asynchronous request made in IssueAsyncRequest():void CMyActive::DoCancel(){iService->CancelAsyncRequest();}Finally, it is a common mistake for developers to declare an unnecessary TRequestStatus member variable in their active object.

Don’t dothis – instead use the one supplied by the CActive base class. Nor is itnecessary to set the iStatus value to KRequestPending after makinga call; the framework sets this value in SetActive().ConsequencesPositives• Especially for applications, where the framework takes care of managing the active scheduler, active objects are simple to create and use.• Active objects are significantly more lightweight than threads, withmuch less RAM overhead.

For example, in Symbian OS the absoluteminimum overhead for a new thread is 9 KB of RAM, approximately20 times the overhead of introducing an active object where the maincost is the additional code size of roughly 500 bytes.12• In most cases, active objects are as effective as multithreading butare easier to debug, which reduces your maintenance and testingcosts. This is not say debugging them is always easy, as stray signals12 Theaverage code size for a class within Symbian OS itself.ACTIVE OBJECTS143can be a pain to track down, however the problems introduced bymultithreading are usually more complex and hard to identify.• The active object priorities provide you with a flexible mechanism forensuring that the important events, such as handling input from theend user, are dealt with before low-priority tasks such as clearing outa cache.• Switching between active objects running in the same thread (whichis the typical use case) avoids the overhead of a thread context switch,so a component that uses this pattern, instead of threads, to managemultiple tasks is normally more efficient.Negatives• Since active objects are cooperatively scheduled, this introducesdependencies between apparently independent parts of a component,so that badly written active objects in one place can cause troubleelsewhere.

Any code, such as that provided in a separate DLL, cancreate an active object and effectively disrupt the entire thread.13• Since this pattern schedules tasks cooperatively, it is not ideal forsituations where real-time responses are required. This is not to say itwon’t work, just that it’ll take some care to set up and especially tomaintain so that alterative scheduling techniques such as pre-emptivemultitasking would probably be more appropriate.• The active scheduler uses a single list to manage its active objectsand is not intended to support a very large number of active objects.Doing so will impact the performance of your thread since the activescheduler must linearly traverse the list of all active objects that itmanages in order to find the correct TRequestStatus to complete,which won’t scale well.• Since this pattern is not directly supported by the standard C++libraries, it is less suitable when porting existing C++ code to or fromSymbian OS.Example ResolvedThe example given above was an application wishing to make a phonecall.

Since this is an asynchronous task, this pattern can be used toencapsulate it within an active object as follows:#include <e32base.h>#include <Etel3rdParty.h>13 If you’re worried that someone might do this deliberately then you shouldn’t load theDLL into your process. See Chapter 7 for alternative ways of tackling this problem.144COOPERATIVE MULTITASKINGclass CDialer : public CActive{public:CDialer(CTelephony& aTelephony);∼CDialer;// Equivalent of IssueAsyncRequest()void Dial(CTelephony::TTelNumber aNumber);private: // From CActivevoid RunL();void DoCancel();private:CTelephony& iTelephony; // Service providerCTelephony::TCallId iCallId;};In this case, we don’t need to do any specific error handling in thisobject, so no RunError() is provided.The constructor is fairly normal since the priority given to the object isEPriorityStandard:CDialer::CDialer(CTelephony& aTelephony): CActive(EPriorityStandard), iTelephony(aTelephony){CActiveScheduler::Add(this);}The Dial() function is where we start the whole process of makinga phone call using CTelephony::DialNewCall().

In particular, youshould note that the TRequestStatus of this object is being passed in,which shows this is an asynchronous call and is how the active schedulerknows which active object initialized this request.In addition, the API takes an output parameter as an argument –iCallId. This is an object of type CTelephony::TCallId and is atoken used to identify the call that you can use if you need to performfurther operations, such as putting the call on hold or hanging up.However, this will not be a valid object until the request has completedso it shouldn’t be accessed until the RunL() fires.

It is also significantthat the object is owned by CDialer rather than just being constructedon the stack, as callParams is below. This ensures that the object isstill in scope by the time the RunL() is called later. This can be quitea subtle bug if you get it wrong because often the service provider hasa higher priority than its clients. Hence in normal operation the servicerequest will cause a context switch to the service provider’s thread whichhandles and completes the request so that when control is returned toACTIVE OBJECTS145your thread, the object on the stack is still in scope. However, this is notguaranteed even now due to priority inversion14 and will be more of aproblem for SMP15 devices in the future.void CDialer::Dial(CTelephony::TTelNumber aNumber){CTelephony::TCallParamsV1 callParams;callParams.iIdRestrict = CTelephony::ESendMyId;CTelephony::TCallParamsV1Pckg callParamsPckg(callParams);iTelephony.DialNewCall(iStatus, callParamsPckg, aNumber, iCallId);SetActive();}In the following function, the request to dial a new call needs to behandled:void CDialer::RunL(){User::LeaveIfError(iStatus); // Rely on the default error handling// The call has been dialled successfully and// iCallId now contains the call’s ID// Update the UI (not shown for brevity)...}We also need to provide a way to cancel the dial request:void CDialer::DoCancel(){// Note that this doesn’t mean "do the cancel asynchronously" but// rather means "cancel the asynchronous request made earlier"iTelephony.CancelAsync(CTelephony::EDialNewCallCancel);}Finally, the destructor simply needs to cancel any outstanding requestssince it doesn’t own any of its own resources:CDialer::∼CDialer(){Cancel();}14 See15 Seeen.wikipedia.org/wiki/Priority inversion.www.symbian.com/symbianos/smp.146COOPERATIVE MULTITASKINGOther Known UsesActive objects are used extensively throughout Symbian OS, so we givejust two examples here:• ServersThis pattern is used extensively within Client–Server (see page 182)with every server object implemented as an active object.

In addition,servers often use additional active objects, called servants, to processclient requests that they can’t satisfy immediately so that they continueto remain responsive to new client requests.• Window ServerThis pattern forms the basis of the Window Server’s event-handlingframework, which handles all application events such as key presses,pointer events, animations, etc.Variants and Extensions• Single Use Active ObjectThis pattern describes an active object as a manager of multipleasynchronous requests on behalf of some client.

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

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

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

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