c# - 如何使函数异步运行

标签 c# .net asynchronous windows-phone async-await

我正在阅读有关异步等待编程的内容,并且对于想要使函数异步运行的场景感到困惑。例如,我想在我的用户界面上显示图像。因此,在 UI 线程上,我调用一个函数,该函数将从存储中获取图像并将图像应用到 UI 上。

正确的做法是什么?

方法1

private async void SetImage()
{
    await Task.Run(() =>
    {
        byte[] fullViewImageBytes = Utils.GetImageFromStorage(fileName);

        if (fullViewImageBytes != null)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                MemoryStream memStream = new MemoryStream(fullViewImageBytes);
                BitmapImage image = new BitmapImage();
                image.SetSource(memStream);
                userImage.Source = image;
            });
        }
    }
}

方法2

private async void SetImage()
{
    await Task.Delay(1);

    byte[] fullViewImageBytes = Utils.GetImageFromStorage(fileName);

    if (fullViewImageBytes != null)
    {
         MemoryStream memStream = new MemoryStream(fullViewImageBytes);
         BitmapImage image = new BitmapImage();
         image.SetSource(memStream);
         userImage.Source = image;
    }
}

最佳答案

由于从磁盘读取文件主要涉及异步 IO,因此您可以利用 Windows Phone 平台提供的各种异步 API。

无需使用Task.Factory.StartNewTask.Run,这意味着根本不需要额外的ThreadPool线程。目前,您的代码并不是真正的异步,请注意,async void 仅适用于顶级事件处理程序,不应在其他情况下使用。

您可以按如下方式利用异步 API:

public async Task<BitmapImage> CreateImageFromFileAsync(string imagePath)
{
    StorageFile storageFile = await StorageFile.GetFileFromPathAsync(imagePath);
    IRandomAccessStream imageFileStream = await storageFile.OpenReadAsync();

    BitmapImage image = new BitmapImage();
    await image.SetSourceAsync(imageFileStream);

    return image;
}

关于c# - 如何使函数异步运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27082190/

相关文章:

.net - Azure AD MSAL 中的范围、角色和组之间的区别

.net - 正则表达式跟踪 `)`

javascript - 即使使用回调函数也无法返回值

javascript - 在node.js服务器中使用https同步读取文件

c# - AutoMapper 一个源对象到多个目标对象

c# - 使用 C# 属性跟踪函数调用、变量和返回值?

c# - 如果 catch 和 finally block 都抛出异常会发生什么?

c# - 异步Client Socket,乱序接收缓冲区数据

c# - 将 CDATA 附加到字符串

c# - MQTTNet 监听主题消息