I was wondering if it was possible to prevent memory of a object (class or struct) from being swapped to disk?
Edit: As for why I\'ve been told some of the data I\'m
You might be looking for the SecureString class, which will not be swapped to disk.
I am still not clear on why you want to do this. In the context of C#, you have to do two things: "pin" the memory so it cannot be relocated by garbage collection, and then lock it so that it doesn't get swapped out.
Here is a nice blog post that describes how to do the first part (pinning):
http://www.matthew-long.com/2005/10/18/memory-pinning/
Now you need the address and extent of the object to be able to invoke VirtualLock
:
http://msdn.microsoft.com/en-us/library/Aa366895
Note that VirtualLock
only locks pages (units of 4K), so your memory area needs to be at least that large, and aligned to the start of a page. I am assuming that it needs to be invoked in an unsafe
context, though I am not sure.
Previous posting on the topic: Prevent an object from being paged out (VirtualLock equivalent)
Another related blog post: http://geekswithblogs.net/robp/archive/2008/08/13/speedy-c-part-3-understanding-memory-references-pinned-objects-and.aspx
Not really, that's an operating system thing.
Just rest assured that Windows' paging strategy will prioritize keeping in memory the most frequently accessed pages, so if a certain page is important for your application, it'll be there as much as possible.
I'd do something totally different:
Build a nice native wrapping C++ DLL with your desired functions/allocations/whatever which will also make sure the data isn't get swapped (VirtualLock as someone said here). Use it from C#.
After all, natively it's possible, it's just that you're now bound to C#. So, get around it!
This is only technically possible. Memory pages can be locked in RAM with the VirtualLock() API function. Problem is, that requires supplying the address of the page(s) you want locked. You can't get this address in any documented way from the garbage collector. Nor does it make any promise that the same address for, say, the gen #0 heap will be repeatable. For one, the size of that heap is dynamic, usually ranging somewhere between 2 and 8 megabytes, depending on the program's allocation pattern.
Just randomly locking a large range with the hope that you'll catch most of them doesn't work either. A process gets a quota of lockable pages. It isn't very large, above all because it is so destabilizing to the operation of the machine. Dragons live here.
Um, good question.. you can disable swap in windows completely (size=0), but idk if thats enough to prevent .NET from swapping.