// Caller must .Ref() public RefCountedImage LoadAsync(string path) { if (!imagesByPath.ContainsKey(path)) { Console.WriteLine($"+{path}"); var rcImage = new RefCountedImage { Path = path }; rcImage.Task = Task.Run(() => { try { return(ResizeToUsefulSize(Image.FromFile(path, true))); } finally { // Loading the image (running this code) takes one reference, being in the cache takes another one, // being used or awaited from the GUI takes a third one. // Making running this code take one reference avoids NPE if the image is evicted before finishing // loading. Console.WriteLine($"@{path}"); rcImage.Unref(); } }); imagesByPath.Add(path, rcImage.Ref()); } return(imagesByPath.TryUse(path)); }
private void ImagesByPath_ElementEvictedEvent(string key, RefCountedImage value) { Console.WriteLine($"-{key}"); value.Unref(); }