我正在app的Suspending事件中保存一个RenderTargetBitmap。如果我打开了应用程序并且在Visual Studio中点击“暂停并关闭”,那么一切都很好。但是如果我首先进入“开始”屏幕或打开另一个应用程序并等待一段时间,换句话说 - 应用程序不在前台,则RenderTargetBitmap.GetPixelsAsync()方法会抛出此COMException,其中包含HResult 0x80004005和“未指定的错误”描述。考虑到在实际使用中,当用户从app切换到其他东西时会发生暂停,这种错误几乎总是发生。我正在保存的RenderTargetBitmap此时不是null,因为我确实检查了它。
我也注意到在开发过程中,有时当我从app切换到其他东西然后回来时,即使应用程序没有被暂停并立即打开,一些图片也不会出现在UI中,就好像它们已经是垃圾一样集。考虑到仍有参考,这很奇怪。不确定它是否与上述问题有关,但似乎可以。
有没有人遇到过类似的问题?当应用程序离开屏幕时,这些图像究竟会发生什么?
修改
这是一个例子。 XAML:
<Grid x:Name="RootGrid" Background="AntiqueWhite">
<Rectangle Width="40" Height="50" Fill="Blue"/>
<Rectangle Width="70" Height="50" Fill="Red" Margin="100 300 0 0"/>
<Rectangle Width="30" Height="60" Fill="Green" Margin="0 0 150 70"/>
<Button x:Name="RenderButton" VerticalAlignment="Top" HorizontalAlignment="Center"
Margin="0 20 0 0" Content="Render" Click="RenderButton_OnClick"/>
</Grid>
代码背后:
private RenderTargetBitmap renderTargetBitmap;
public MainPage()
{
InitializeComponent();
Application.Current.Suspending += CurrentOnSuspending;
}
private async void RenderButton_OnClick(object sender, RoutedEventArgs args)
{
this.renderTargetBitmap = new RenderTargetBitmap();
await this.renderTargetBitmap.RenderAsync(RootGrid);
}
private async void CurrentOnSuspending(object sender, SuspendingEventArgs args)
{
var defferal = args.SuspendingOperation.GetDeferral();
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"render.png", CreationCollisionOption.ReplaceExisting);
await SaveToFileAsync(this.renderTargetBitmap, file);
defferal.Complete();
}
private async Task SaveToFileAsync(RenderTargetBitmap image, IStorageFile file)
{
using (var stream = await file.OpenStreamForWriteAsync())
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream.AsRandomAccessStream());
var pixels = await image.GetPixelsAsync();
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
(uint)image.PixelWidth, (uint)image.PixelHeight, 96, 96, pixels.ToArray());
await encoder.FlushAsync();
}
}
在移动设备上启动应用,点击“渲染”按钮。之后按“开始”将应用程序关闭屏幕,等待一段时间(10秒钟即可),然后在Visual Studio的“调试位置”栏中按“暂停并关闭”。观察COMException。