Windows Phone 8.1 BitmapDecoder async/await not st

2019-09-20 15:58发布

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条回答
forever°为你锁心
2楼-- · 2019-09-20 16:24

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.

查看更多
登录 后发表回答