Search code examples
c#memorygarbage-collectionmemory-pool

Memory pool for object with different size - C#


Do you have some solution, how to make object pool (memory pool) with objects than can contain different data with different size ? So if I request for object in memory pool with some size, it returns to me some allocated memory chunk with the closest size to my request. It should be written in C#. Thank you, because I really dont exactly know, what is the best collection for this and best algorithm. In C++ there are some solutions but there is no memory pool for C#.


Solution

  • .Net Framework already has such an implementation (used by Windows Communication Foundation). See BufferManager

    var buffMgr = BufferManager.CreateBufferManager(
                     104857600, // use no more than 100 MB in total
                     10485760);  // allocate 10 MB max to each buffer
    var buff = buffMgr.TakeBuffer(65535); // allocate a buffer enough to fit a 65 KB object
                               // note: this could return a buffer bigger than 65 KB 
    
    //when done with the buffer:
    buffMgr.ReturnBuffer(buff);