0

async我在编写检索Image表单的方法时遇到问题WebCam

我这样称呼这个方法:

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

我得到错误:

错误 3 无法将类型“System.Threading.Tasks.Task”隐式转换为“System.Windows.Media.ImageSource”

而且不知道为什么,因为我返回了同样的东西。

4

1 回答 1

1

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

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

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

函数的结果LoadBitmapAsync是一个任务,您需要在将其分配给Source属性之前等待其结果。

于 2013-04-07T10:50:58.307 回答