Garbage Collection LOH, WeakReferences, Large Objects

In my application, I need to load large files (maybe about ~ 250 MB) into memory, I do it in a lazy way - when the user asks to see the file, I load it. After that, every time the user tries to access the file, I can show it immediately, because it is already in memory. So, the problem is garbage collection ... Each file that I upload, I upload through WeakReference, BUT: I tested it several times, I was able to load about 3 GB into memory (which made the application unusable), but the GC did not happen. I can’t name GC.Collect (2) because I can’t determine the time to call it, so how can I tell GC to collect memory (weak links) at good moments (hell, 3GB is too much ... it seems GC just doesn’t execute your work) Hot,to solve this? I really need lazy loading, but I need memory to collect when the process uses more than 1 GB, or something like that

+3
source share
1 answer

There is a static function called GC.GetTotalMemory(bool forceFullCollection)( http://msdn.microsoft.com/en-us/library/system.gc.gettotalmemory.aspx ). You can use it to force garbage collection before loading a new file into memory if you pass some threshold.

Edit: possible implementation

public MyFile GetMyFile(){
   if ( !is_my_file_in_memory() ) {
      if (CG.GetTotalMemory(false) > MY_THRESHOLD ) {

        GC.Collect(2);

      }
      load_my_file_in_memory();
   }
   return get_my_file_from_memory();
}
+1
source

Source: https://habr.com/ru/post/1795544/


All Articles