If your problem was that your process was getting its WS trimmed too agressively in low-memory situations, you could take care of it by calling SetProcessWorkingSetSize
or just setting Process.CurrentProcess.MinWorkingSet.
What you've shown, though, is that your working set is getting reduced by a GC. This tells me that what's really happening is the GC is deallocating the pages that make up your WS. If this is the case, you have an address space problem rather than a working set problem, and there's no system call you can make to prevent it. Ideally you would be able to tell the GC not to return its memory to the OS, but .NET doesn't have a feature like that.
To solve an address space problem you will have to reuse objects you have already allocated. If your problem is with the Large Object Heap, it's most likely due to collections. For example, rather than creating a new array/list/dictionary, call its Clear
method and reuse it. If your problem is strings, you might be able to get away with using StringBuilder
s to stay out of the LOH.
If you have certain types of object you create lots of, consider creating a pool of them that get recycled. I've never done such a thing, but if I were to implement it I would create an object with a static factory method that pulls objects out of a pool and calls an initializer instead of having public constructors, and put a finalizer on it that puts it back in the pool and nulls out any references in it. Depending on the needs, the pool might be a ConcurrentBag<WeakReference<T>>
.