【问题标题】:Windows Phone 8.1 BitmapDecoder async/await not stepping through the entire functionWindows Phone 8.1 BitmapDecoder async/await 不单步执行整个函数
【发布时间】:2015-03-16 05:37:53
【问题描述】:

这是对我之前在here 发布的问题的回答的后续。

我将建议的答案放入异步函数中:

public static async Task<int[]> bitmapToIntArray(Image bitmapImage)       
    {
        string fileName = "/Images/flowers.jpg";

        StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
        IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

        var pixelData = await decoder.GetPixelDataAsync();
        var pixels = pixelData.DetachPixelData();

        var width = decoder.OrientedPixelWidth;
        var height = decoder.OrientedPixelHeight;

        int[] colors = new int[width * height];


        for (var i = 0; i < height; i++)
        {
            for (var j = 0; j < width; j++)
            {
                byte r = pixels[(i * height + j) * 4 + 0]; //red
                byte g = pixels[(i * height + j) * 4 + 1]; //green
                byte b = pixels[(i * height + j) * 4 + 2]; //blue (rgba)

                colors[i * height + j] = r;
            }
        }

        return colors;
    }

它是从下面的主函数调用的:

public void ApplyImageFilter(Image userImage, int imageWidth, int imageHeight)
    {
        ...
        int[] src = PixelUtils.bitmapToIntArray(userImage).Result;
        ...
        ;
    }

但是,当我踏入上面那一行时,发生的情况是,只有 bitmapToIntArray 函数的第二行:

StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);

一直等到完成,然后它跳回 ApplyImageFilter 并逐步执行该函数的其余部分(并在最后给出错误)。在 bitmapToIntArray 函数中的第一个 await 之后,它不会进入任何行。我已经将 async/await 与我之前成功完成的项目进行了比较,似乎我两次都遵循了相同的程序。还阅读了异步/等待功能并使用了一些代码,但没有运气。我不知道我还能尝试什么,所以任何建议都将不胜感激。

【问题讨论】:

  • 听起来下游代码依赖于 PixelUtils.bitmapToIntArray() 的结果,但它还没有完成,所以没有结果。因此,您应该等待 PixelUtils.bitmapToIntArray() 返回结果,然后再继续该方法的其余部分。

标签: c# windows-phone-8.1 async-await imagefilter


【解决方案1】:

您正在通过调用 Result 阻塞 UI 线程。

一个你去异步,你必须一直去异步。

public async Task ApplyImageFilter(Image userImage, int imageWidth, int imageHeight)
{
    ...
    int[] src = await PixelUtils.bitmapToIntArray(userImage);
    ...
}

有关async-await 的更多信息,请阅读the articles on my curation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-27
    • 2019-11-06
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2015-05-04
    • 1970-01-01
    相关资源
    最近更新 更多