MonoTouch: App killed for low mem, Why? Live bytes allocation 5 MB top

好久不见. 提交于 2019-11-30 15:49:06
Javier Xamarin

I had problems with UIImage.FromFile. My app is loading a lot of png images using a task, and showing it in the main thread.

I added a GC.Collect in the background task, but it hasn't fixed the problem. I had to remove the background task, do all the stuff in the main thread AND call GC.Collect. It seems that Image.Dispose is not releasing the image memory :(

But it doesn't work when you have another task, so i had to remove it :(

Yes it is not working....

You need to use NSAutoreleasePools around your image creation code, something like this:

void PerformLoadImageTask(CancellationToken token)
{
    if (token.IsCancellationRequested)
    {
         Console.WriteLine("Task {0}: Cancelling", Task.CurrentId);
         return;
    }

    using (var pool = new NSAutoreleasePool ()) {
        current_uiimage_A = UIImage.FromFileUncached(file_name);
        page_A_image_view.Image = current_uiimage_A;
    }
}

For some APIs that create objects the object will be added to the autorelease pool, and not released until the pool is drained. MonoTouch automatically creates autorelease pools for all user threads (including threadpool, TPL and normal System.Threading threads), but these pools aren't drained until the thread exits (which you can't control in the case of threadpool and TPL threads). So the solution is to use a NSAutoreleasePool around the critical code (the pool will automatically be drained when disposed).

This is interesting for me, I am just starting to look at memory management, I'm not even sure if it's essential to null and object and call dispose, because the scoping rules should do the job for you? However it will help the garbage collector to do it ASAP.

Explicitly asking for the garbage collector to run is a request, not a guarantee.

I would guess that an object created on the ui thread is being referenced in one outside of the ui thread and would look there, but I'm not sure.

I look forward to seeing an update in this as I'm sure that I will experience similar problems!

Good luck, Rob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!