WPF Image.Source缓存过于激烈

Han*_*ank 9 .net wpf caching

我有一个实例System.Windows.Controls.Image,我以编程方式设置内容:

Uri location = new Uri(uriString);
image.Source = new BitmapImage(location);
Run Code Online (Sandbox Code Playgroud)

有时我知道服务器上的图像已经改变了,我想要刷新它,但每次重复上面的代码我得到相同的图像.

这似乎是一个缓存问题,但两个明显的解决方案 - RequestCacheLevel而且BitmapCacheOption- 似乎什么都不做.此代码具有相同的结果:

var cachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore)) {
    CacheOption = BitmapCacheOption.None
};
image.Source = new BitmapImage(location, cachePolicy);
// Still uses the cached version.
Run Code Online (Sandbox Code Playgroud)

我发现强制刷新的唯一方法是将一个抛弃的查询字符串附加到URI,这似乎有效,但也是一个完整的黑客攻击:

Uri location = new Uri(uriString + "?nonsense=" + new Random().Next());
image.Source = new BitmapImage(location);
// This forces a refresh
Run Code Online (Sandbox Code Playgroud)

如何防止这些图像被缓存和/或强制刷新?

Col*_*sen 23

我认为你需要将BitmapImage上的CreateOptions设置为:

BitmapCreateOptions.IgnoreImageCache
Run Code Online (Sandbox Code Playgroud)

  • 是的,这解决了!呃,为什么有那么多的缓存选项? (3认同)