I would like to limit how much RAM a thread in C# can allocate, such that allocations beyond this limit will fail/crash or the thread will terminate.
So for example, suppose that I have 3 managed threads in C#, threads A, B, and C. I want to limit all three threads to not use more than 100 MB of RAM. If they do, then I want them to crash without impacting the other threads.
Now it seems to me that since C# is a virtual machine-based language, and uses a garbage collector, this should actually be theoretically possible without trying to use OS features that limit process RAM usage.
How can something like this be achieved? Any guidance would be greatly appreciated.
CodePudding user response:
You can't limit the RAM used by a thread, or a group of threads, because the only RAM that is owned by a thread is its stack (around 1MB of memory). The memory that is allocated in the heap is shared by all threads of the program. It's not owned by any thread or groups of threads. There is no provision in the C# language or the .NET runtime for preventing a specific thread from interacting with an object allocated in the heap. If you want to limit the amount of RAM that is available for an operation, you must isolate this operation in a separate process, not a separate thread.