Search code examples
.netmemory-managementclrclr-hosting

How to limit a memory that can be allocated by a specific class?


I'm loading several external assemblies into my application at runtime. And I need to limit an amount of memory that can be used by a specific class which is defined in each of the external assemblies, for example, 10 mb per instance, otherwise we get OutOfMemory.

I've googled what is the best way to do this and found some information about CLR Runtime Hosting. It seems to be the thing I need, but I can not find any good examples.

Can anyone share the examples of code or maybe some links about memory management using CLR Runtime Hosting? Or maybe there are some better solutions to limit an amount of memory per class?

Thanks in advance.


Solution

  • This is not something you will be able to do through CLR Hosting. If you host the CLR, you can fulfill allocation requirements from the GC to Windows, e.g. so that instead of VirtualAlloc it uses some other allocator. However, the host is not invoked every time an object is allocated (this would be too expensive).

    You could theoretically accomplish this by using the CLR Profiling API. It does allow you to receive a callback whenever an object is allocated.

    I'm afraid, though, that you're trying to look at this from the wrong perspective. Instead of limiting the amount of memory used by instances of a class, which is very granular, could you instead try and isolate these external assemblies into separate processes, possibly even limiting them using the Win32 Job Object APIs?