Skip to content

Commit

Permalink
Dispose images on Main-Thread in MvxImageCache to avoid crashes relat…
Browse files Browse the repository at this point in the history
…ed to dispose/render thread race

Fix to MvvmCross#41
  • Loading branch information
Seifer committed Mar 22, 2016
1 parent cea5168 commit 1bde2ef
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions DownloadCache/MvvmCross.Plugins.DownloadCache/MvxImageCache.cs
Expand Up @@ -93,21 +93,41 @@ private void ReduceSizeIfNecessary()
// we don't use LINQ OrderBy here because of AOT/JIT problems on MonoTouch
entries.Sort(new MvxImageComparer());
var entriesToRemove = new List<Entry>();
while (currentCountFiles > _maxInMemoryFiles
|| currentSizeInBytes > _maxInMemoryBytes)
{
var toRemove = entries[0];
entries.RemoveAt(0);
entriesToRemove.Add (toRemove);
currentSizeInBytes -= toRemove.Image.GetSizeInBytes();
currentCountFiles--;
if (_disposeOnRemove)
toRemove.Image.RawImage.DisposeIfDisposable();
var entriesByUrl = _entriesByHttpUrl.Remove (toRemove.Url);
Interlocked.Exchange (ref _entriesByHttpUrl, entriesByUrl);
}
if (_disposeOnRemove && entriesToRemove.Count > 0)
{
// It is important to Dispose images on UI-thread
// otherwise there could be a crash when the image could be disposed
// just about to be rendered
// see https://github.com/MvvmCross/MvvmCross-Plugins/issues/41#issuecomment-199833494
DisposeImagesOnMainThread (entriesToRemove);
}
});
}

private void DisposeImagesOnMainThread (List<Entry> entries)
{
InvokeOnMainThread (() => {
foreach (var entry in entries)
{
entry.Image.RawImage.DisposeIfDisposable();
}
});
}

Expand Down

0 comments on commit 1bde2ef

Please sign in to comment.