【问题标题】:WinRT App hangs when BitmapDecoder.CreateAsync(stream) is called调用 BitmapDecoder.CreateAsync(stream) 时 WinRT 应用程序挂起
【发布时间】:2012-09-12 12:45:28
【问题描述】:

我有以下方法传递一个加载了 JPEG 数据的 InMemoryRandomAccessStream:

private async Task<byte[]> GetDataAsync(IRandomAccessStream stream)
{
    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

    BitmapFrame frame = await decoder.GetFrameAsync(0);

    BitmapTransform transform = new BitmapTransform()
    {
        ScaledWidth = decoder.PixelWidth,
        ScaledHeight = decoder.PixelHeight
    };

    PixelDataProvider pixelData = await frame.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);

    return pixelData.DetachPixelData();
}

此方法一直挂起,除非我在第一行设置断点并遍历每一行。我尝试使用不同的 JPEG 图像,修改“GetPixelDataAsync”的参数并在行之间临时插入“await Task.Delay(...)”,但没有任何帮助。该应用程序执行许多其他耗时的异步操作,并且除了这部分之外工作正常。目前尚不清楚为什么设置断点(除了它会产生一些时间延迟)使其工作。

请帮忙解决这个问题。

【问题讨论】:

  • 你能说明你是如何调用这个方法的吗?

标签: c# windows-runtime winrt-async


【解决方案1】:

我猜是在野外,但我有同样的problem

我认为您从同步上下文中调用此异步方法,例如:

private void ButtonClick(...) 
{
  var bytes = GetDataAsync(...);
}

这将导致您的应用程序在 UI 线程中运行,从而导致死锁。要么使调用方法也异步,要么使用 ConfigureAwait(false):

private async Task<byte[]> GetDataAsync(IRandomAccessStream stream)
{
    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream).AsTask().ConfigureAwait(false);

    BitmapFrame frame = await decoder.GetFrameAsync(0).AsTask().ConfigureAwait(false);

    BitmapTransform transform = new BitmapTransform()
    {
        ScaledWidth = decoder.PixelWidth,
        ScaledHeight = decoder.PixelHeight
    };

    PixelDataProvider pixelData = await frame.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage).AsTask().ConfigureAwait(false);

    return pixelData.DetachPixelData();
}

也许可以在这里看看这个非常好的 explanation 使用 async/await 并获得死锁。

【讨论】:

  • 我改用了 WritableBitmap 方法。但是,与 ConfigureAwait(false) 一起出现的 UI 死锁问题似乎是一个合理的解决方案。谢谢你,劳比!
  • 对我不起作用。仍然坚持原来的 OP 场景。
  • explanation 链接现已失效。任何人都知道从哪里获得新链接。或者更好的是,将解释作为答案的一部分?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-11
  • 2016-09-05
  • 2012-08-15
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
相关资源
最近更新 更多