Windows Phone 8.1 BitmapDecoder async/await not stepping through the entire function

北城余情 提交于 2019-12-13 10:31:42

问题


This is a follow up to an answer to a question I had previously posted here.

I put the suggested answer into an async function:

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;
    }

It is being called from the main function below:

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

However, when I step into the line above, what happens is that only the second line of the bitmapToIntArray function:

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

is waited until done, and then it jumps back to the ApplyImageFilter and steps through the rest of that function (and gives an error at the end). It doesn't go to any line after the first await in the bitmapToIntArray function. I've compared async/await with a previous project I did successfully and it seems like I followed the same procedure both times. Also read up on async/await functionality and played around with the code a bit but had no luck. I'm at a loss on what else I can try, so any suggestions will be greatly appreciated.


回答1:


You are blocking the UI thread by calling Result.

One you go async, you must go async all the way.

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

For more information on async-await, read the articles on my curation.



来源:https://stackoverflow.com/questions/29055689/windows-phone-8-1-bitmapdecoder-async-await-not-stepping-through-the-entire-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!