0

I have a service that runs on a domain controller that is randomly accessed by other computers on the network. I can't shutdown the service and run it only when needed (this would defeat the purpose of running it as a service anyway). The problem is that the memory used by the service doesn't seem to ever get cleared, and increases every time the service is queried by a remote computer. Is there a way to set a limit on the RAM used by the application?

I've found a few references to using MaxWorkingSet, but none of the references actually tell me how to use it. Can I use MaxWorkingSet to limit the RAM used to, for example, 35MB? and if so, how? (what is the syntax etc?)

Otherwise, is there a function like "clearall()" that I could use to reset the variables and memory at the end of each run through? I've tried using GC.Collect(), but it didn't work.

SeanD
  • 3
  • 2

1 Answers1

0

Literally, MaxWorkingSet only affect Working set, which is the amount of physical memory. To restrict of an overall memory usage, you need Job Object API. But it is danger if your program really need such memory (many codes don't consider an OutOfMemoryException and sometimes .NET runtime has strange behaviors when memory is not enough)

You need to:

  • Create a Win32 Job object
  • Set the maximum memory to the job
  • Assign your process to the job

Here is a wrapper for .NET. ^reference

Besides, you could try this method of GC: (for .NET 4.6 or newer)

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect(2, GCCollectionMode.Forced, true, true);

(for older but sometimes doesn't work)

GC.Collect(2, GCCollectionMode.Forced);

The third param in 4.6 version of GC.Collect() is to tell runtime whether to do garbage collecting immediately. In older versions, GC.Collect() only notifies and leaves the decision to runtime.

As for some programming advice, I suggest you could wrap a class for one query. The class could be explicitly disposed after a query is done. It may help make GC smarter.

Finally, indeed there are something in .NET framework which you need to manage yourself. Like Bitmap.GetHBitmap, they need to be disposed manually.

Community
  • 1
  • 1
Keyu Gan
  • 711
  • 5
  • 17