Requesting RAM Asynchronously

This section describes how an application can request for free RAM asynchronously.

Perform the steps described in Allowing Large Memory Allocation .

Requesting free RAM asynchronously is recommended as the application is not blocked during the method call handling.

  1. Start an asynchronous request for a block of memory.
            CMemoryAllocatingObject::StartFunctionalityRequiringAllocationL()
        {
        User::LeaveIfError(iOomMonitorSession.Connect());
        iMemoryRequester = CMemoryRequester::NewL(iOomMonitorSession, *this);
        iMemoryRequester->Start(KLargeValueToAllocate);
        }
           
  2. Implement the active object and request for free memory.
            void CMemoryRequester::Start(TInt aBytesRequested)
        {
        iOomMonitorSession.RequestFreeMemory(aBytesRequested, iStatus);    
        SetActive();
        }
           

The following code snippet illustrates an asynchronous request for free RAM allocation:

       const TInt KLargeValueToAllocate = 2097152; //2MB

// Start an asynchronous request for block of memory
CMemoryAllocatingObject::StartFunctionalityRequiringAllocationL()
    {
    User::LeaveIfError(iOomMonitorSession.Connect());
    iMemoryRequester = CMemoryRequester::NewL(iOomMonitorSession, *this);
    iMemoryRequester->Start(KLargeValueToAllocate);
    }

// Called when the asynchronous request is completed
CMemoryAllocatingObject::MemoryRequestCompleteL(TInt aResult)
    {
    if (aResult == KErrNone)
        {
        DoFunctionRequiring_KLargeValueToAllocate_BytesL();
        }
    iOomMonitorSession.Close();
    }
The active object implementation is the following:

// Start an asynchronous request for block of memory
void CMemoryRequester::Start(TInt aBytesRequested)
    {
    iOomMonitorSession.RequestFreeMemory(aBytesRequested, iStatus);    
    SetActive();
    }
    

// Called when the asynchronous request is completed
void CMemoryRequester::RunL()
    {
    iObserver.MemoryRequestCompleteL(iStatus.Int());
    }