Async, await不能隐式转换Task

本文关键字:转换 Task 不能 await Async | 更新日期: 2023-09-27 18:07:47

我在编写async方法时遇到了麻烦,该方法从WebCam检索Image

我这样调用这个方法:
void webcam_ImageCaptured(object source, WebcamEventArgs e)
{
    _FrameImage.Source = Helper.LoadBitmap((System.Drawing.Bitmap)e.WebCamImage);
}

:

public static BitmapSource LoadBitmap(System.Drawing.Bitmap source)
{
    ip = source.GetHbitmap();
    bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, System.Windows.Int32Rect.Empty,
    System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    DeleteObject(ip);
    return bs;
 }

上面的代码可以工作(它来自库),我试着这样写:

public async static Task<BitmapSource> LoadBitmap(System.Drawing.Bitmap source) 
{
    return await Task.Run(() =>
    {
        ip = source.GetHbitmap();
        bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, System.Windows.Int32Rect.Empty,
        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
        DeleteObject(ip);
        return bs;
    });
}

得到error:

错误3无法隐式转换类型"System.Threading.Tasks"。任务"到"System.Windows.Media。ImageSource '

不知道为什么,因为我返回相同的东西

Async, await不能隐式转换Task

在我看来,你的错误是在第一个代码片段,它应该是:

_FrameImage.Source = await Helper.LoadBitmapAsync((System.Drawing.Bitmap)e.WebCamImage);

我已经添加了await关键字和Async后缀(根据Filip的建议)。

LoadBitmapAsync函数的结果是一个任务,您需要等待它的结果,然后再将其分配给Source属性

相关文章: