使用.NET / WPF预加载图像资源

Ron*_*ARP 5 c# wpf asynchronous image preload

我想在应用程序启动时预加载图像资源。图像应缓存在应用程序内存中。因此,我可以在应用程序中使用预加载的图像。

问题是,如果我加载一个特定的具有很多图像的视图,应用程序将挂起几秒钟,然后该视图就会出现。该应用程序是基于XAML的,但是图像控件的源属性是动态更改的。

我已经测试了几件事,但似乎没有任何效果。

var uri = new Uri ( "pack://application:,,,/Vibrafit.Demo;component/Resources/myImage.jpg", UriKind.RelativeOrAbsolute ); //unit.Image1Uri;
var src = new BitmapImage ( uri );
src.CacheOption = BitmapCacheOption.None;
src.CreateOptions = BitmapCreateOptions.None;

src.DownloadFailed += delegate {
    Console.WriteLine ( "Failed" );
};

src.DownloadProgress += delegate {
    Console.WriteLine ( "Progress" );
};

src.DownloadCompleted += delegate {
    Console.WriteLine ( "Completed" );
};
Run Code Online (Sandbox Code Playgroud)

但不会加载该图像。加载图像的唯一方法是将其显示在图像控件的屏幕上,并将源属性分配给我新创建的BitmapImage对象。但是我不想在启动时显示所有图像。

Jcl*_*Jcl 1

如果您希望图像立即加载,则需要设置此缓存选项:

src.CacheOption = BitmapCacheOption.OnLoad;
Run Code Online (Sandbox Code Playgroud)

否则,它会在您第一次访问数据时按需加载(或者,在您的情况下,每次您尝试访问图像数据时,因为您选择的是None)。

查看文档

另外,您要在设置缓存选项UriSource 之前进行设置。所以尝试类似的东西(在我的脑海中,现在无法测试):

var uri = new Uri ( "pack://application:,,,/Vibrafit.Demo;component/Resources/myImage.jpg", UriKind.RelativeOrAbsolute ); //unit.Image1Uri;
var src = new BitmapImage ();
src.BeginInit();
src.CacheOption = BitmapCacheOption.OnLoad;
src.CreateOptions = BitmapCreateOptions.None;
src.DownloadFailed += delegate {
    Console.WriteLine ( "Failed" );
};

src.DownloadProgress += delegate {
    Console.WriteLine ( "Progress" );
};

src.DownloadCompleted += delegate {
    Console.WriteLine ( "Completed" );
};
src.UriSource = uri;
src.EndInit();
Run Code Online (Sandbox Code Playgroud)