简体   繁体   中英

Xamarin - How to properly dispose bitmaps?

I'm new to App development and I have some predicaments. I have a method that downloads an image from a server and then turns it into a bitmap so I can assign it to an ImageView. The problem is that if I call it for more than 10 times the app crashes with an OutOfMemory exception. I tried removing the old Bitmap with Dispose() , but it doesn't work as expected. Any way to fix this? Code:

/...
string url = deviceModel.LastPhotoLink;
Bitmap imageBitmap = await new ImageDownloader().GetImageBitmapFromUrlAsync(url, Activity);
lastPhoto.SetImageBitmap(imageBitmap);
imageBitmap.Dispose();
/...

public async Task<Bitmap> GetImageBitmapFromUrlAsync(string url, Context context) {
     WebClient client = new WebClient();
     ISharedPreferences pref = context.GetSharedPreferences("UserSession", FileCreationMode.Private);
     string cookie = pref.GetString("PHPSESSID", string.Empty);
     client.Headers.Add(HttpRequestHeader.Cookie, "PHPSESSID=" + cookie);
     var imageBytes = await Task.Run(() => client.DownloadData(url));
     Bitmap imageBitmap = await Task.Run(() => BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length));

return imageBitmap;
}

Are there any objects with references to the Bitmaps after you call Dispose()? Calling dispose on an object is not guaranteed to free all the memory, you still have to remove references so the garbage collector can do its work.

MSDN article for Bitmap Dispose

relevant section:

After calling Dispose, you must release all references to the Image so the garbage collector can reclaim the memory that the Image was occupying. For more information, see Cleaning Up Unmanaged Resources and Implementing a Dispose Method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM