ENTERPRISE

Memory Management : Prevent Memory from Being Moved, Allocate Unmanaged Memory

10/4/2012 3:50:35 AM

Prevent Memory from Being Moved

Scenario/Problem:You need to force an object to remain in its memory location, especially for interop with native code.

When the garbage collector runs, it moves objects around in memory in a compaction process. This requires fixing up all the memory addresses for all the moved objects. Obviously, this is not possible for objects the GC does not know about—such as in a native code interop situation.

Solution:“Fix” the memory in place.
int[] vals = new int[10];
//the location of vals is fixed for the duration of the block
fixed (int* pI = &vals[0])
{
    pI[i] = 13;
}

Note

You should keep memory fixed only as long as you absolutely need to. While memory is fixed in place, the GC is less efficient as it attempts to work around the unmovable block.

Allocate Unmanaged Memory

Scenario/Problem:You need a buffer of memory that unmanaged code can access and you don’t want the GC involved at all.
Solution:Use the Marshal.AllocHGlobal() method and manually add some memory pressure:
unsafe class MyDataClass
{
    IntPtr _memory = IntPtr.Zero;

    public int NumObjects { get; private set; }
    public int MemorySize { get { return sizeof(Int32) * NumObjects; } }

    public MyDataClass(int numObjects)
    {
        this.NumObjects = numObjects;

        _memory = Marshal.AllocHGlobal(MemorySize);
        //we should tell the garbage collector that we are using more
        //memory so it can schedule collections better
        //(note--it still doesn't change the amount
        //that GC.GetTotalMemory returns)
        GC.AddMemoryPressure(MemorySize);

        Int32* pI = (Int32*)_memory;
        for (int i = 0; i < NumObjects; ++i)
        {
            pI[i] = i;
        }
    }

    //unmanaged resources need a finalizer to make
    //sure they're cleaned up!
    ~MyDataClass()
    {
        if (_memory != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(_memory);
            //tell garbage collector memory is gone
            GC.RemoveMemoryPressure(MemorySize);
        }
    }
}

					  

When you allocate memory in this way, .NET knows nothing about it, as this program snippet shows:

static void Main(string[] args)
{
    Console.WriteLine("Memory usage before unmanaged allocation: {0:N0}", GC.GetTotalMemory(false));
    MyDataClass obj = new MyDataClass(10000000);

    //unmanaged memory is not counted!
    Console.WriteLine("Memory usage after unmanaged allocation: {0:N0}", GC.GetTotalMemory(false));
}

					  

The output is as follows:

Memory usage before unmanaged allocation: 665,456
Memory usage after unmanaged allocation: 706,416

The AddMemoryPressure method notifies the CLR that it should take this into account when scheduling garbage collection, but that is all the involvement it has. When your unmanaged memory is freed, you should release this pressure.

Other  
  •  Memory Management : Use Pointers, Speed Up Array Access
  •  Memory Management : Force a Garbage Collection, Create a Cache That Still Allows Garbage Collection
  •  D-Link Cloud Router 5700 With 1750Mbps Total Band
  •  The HP Virtual Server Environment : Virtual Partitions (Peak Performance Virtualization)
  •  The HP Virtual Server Environment : nPartitions (Electrically Isolated Hardware Partitions)
  •  The HP Virtual Server Environment : The Partitioning Continuum at a Glance
  •  IBM WebSphere Process Server 7 and Enterprise Service Bus 7 : Monitoring WPS/WESB applications
  •  Microsoft Dynamics Sure Step 2010 : The Microsoft Solution Selling Process
  •  Microsoft Dynamics Sure Step 2010 : Solution selling concepts
  •  Microsoft Dynamics Sure Step 2010 : Driving value for the customer and the solution provider
  •  
    Video
    Video tutorials
    - How To Install Windows 8

    - How To Install Windows Server 2012

    - How To Install Windows Server 2012 On VirtualBox

    - How To Disable Windows 8 Metro UI

    - How To Change Account Picture In Windows 8

    - How To Unlock Administrator Account in Windows 8

    - How To Restart, Log Off And Shutdown Windows 8

    - How To Login To Skype Using A Microsoft Account

    - How To Enable Aero Glass Effect In Windows 8

    - How To Install Windows Store Apps From Windows 8 Classic Desktop

    - How To Disable Windows Update in Windows 8

    - How To Disable Windows 8 Metro UI

    - How To Add Widgets To Windows 8 Lock Screen

    - How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010
    programming4us programming4us
    Top 10
    Free Mobile And Desktop Apps For Accessing Restricted Websites
    MASERATI QUATTROPORTE; DIESEL : Lure of Italian limos
    TOYOTA CAMRY 2; 2.5 : Camry now more comely
    KIA SORENTO 2.2CRDi : Fuel-sipping slugger
    How To Setup, Password Protect & Encrypt Wireless Internet Connection
    Emulate And Run iPad Apps On Windows, Mac OS X & Linux With iPadian
    Backup & Restore Game Progress From Any Game With SaveGameProgress
    Generate A Facebook Timeline Cover Using A Free App
    New App for Women ‘Remix’ Offers Fashion Advice & Style Tips
    SG50 Ferrari F12berlinetta : Prancing Horse for Lion City's 50th
    Popular Tags
    Video Tutorail Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Exchange Server Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe Photoshop CorelDRAW X5 CorelDraw 10 windows Phone 7 windows Phone 8 Iphone