开发者

Garbage collection of LOH, WeakReferences, large objects

开发者 https://www.devze.com 2023-02-13 23:53 出处:网络
In my application I need to load large files (can beabout ~ 250 MB) into memory, I\'m doing it in a lazy way - when user ask to see a file - I\'m loading it. After that, every time user tries to acces

In my application I need to load large files (can be about ~ 250 MB) into memory, I'm doing it in a lazy way - when user ask to see a file - I'm loading it. After that, every time user tries to access the file, I'm able to show it immediately , because it's already located in memory. So, The problem is with garbage collection... Every file I'm loading, I'm loading through a WeakReference, BUT : I tested It a few times, I was able to load about 3GB into memory (than app become not usable), but GC did not occ开发者_如何学Gourred. I'm not able to call GC.Collect(2), because I can not determine time to call it, so how to tell GC to collect memory (weakreferences) in good moments (damn, 3GB is too much...It seems GC just does not doing his job) Hot to resolve it? I really need lazy loading, but I need memory to be collected when process uses more than 1GB of it, or something like that


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 a Garbage Collection before loading a new file into the memory, if you have passed some threshold.

Edit: a 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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消