【问题标题】:await and async not working in Xamarin.UWP等待和异步在 Xamarin.UWP 中不起作用
【发布时间】:2018-01-02 22:08:56
【问题描述】:

我正在使用 async 和 await 来获取按钮的流。 async 方法工作正常,当我使用 await 时,它返回函数。所以我总是在内存流中获取 null 值。

当我使用这个 (await renderTargetBitmap.RenderAsync(button)) 操作意味着它返回语句而不进行计算。

任何人,请建议我如何解决这个问题?我需要添加任何其他代码吗?

这是我的代码:

 public class StreamDependencyService: IStreamDependency
{
    Button button;
    public Stream GetStream()
    {
        button = new Button() { Height = 50, Width = 50, Content = "Click" };
        return GetStream_UWP().Result;
    }
    public async Task<Stream> GetStream_UWP()
    {
        Stream memoryStream ;
        var renderTargetBitmap = new RenderTargetBitmap();
        await renderTargetBitmap.RenderAsync(button);
        var pixels = await renderTargetBitmap.GetPixelsAsync();
        Guid encoderId = BitmapEncoder.JpegEncoderId;
        using (memoryStream = new MemoryStream())
        {
            var encoder = await BitmapEncoder.CreateAsync(encoderId, memoryStream.AsRandomAccessStream());
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth,
                (uint)renderTargetBitmap.PixelHeight, 96.0, 96.0, pixels.ToArray());

            await encoder.FlushAsync();

        }
        return memoryStream;
    }
}

【问题讨论】:

    标签: uwp xamarin.forms cross-platform


    【解决方案1】:

    不要使用GetStream_UWP().Result,你的代码会死锁。

    等待按钮首先加载并在 Loaded 事件中,await on GetStream_UWP()

    button.Loaded += async (s, e) => await GetStream_UWP();
    

    【讨论】:

    • 谢谢,我试过了,我仍然面临这个问题。如果我将 GetStream_UWP() 方法更改为 void 意味着它可以工作,否则它会在 await 方法到来时返回语句。
    猜你喜欢
    • 2023-04-07
    • 2019-03-17
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多