简体   繁体   中英

Async, await cannot implicity convert Task

I have trouble with writing async method that retrieves Image form WebCam .

I call this method like this:

void webcam_ImageCaptured(object source, WebcamEventArgs e)
{
    _FrameImage.Source = Helper.LoadBitmap((System.Drawing.Bitmap)e.WebCamImage);
}

And:

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

Code above works (it is from library), I tried to write this:

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

And I get error:

Error 3 Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'System.Windows.Media.ImageSource'

And have no idea why, because I returning the same thing.

The way I see it, your error is in the first code snippet, it should be:

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

I've added await keyword and Async suffix (as per Filip's recommendation).

The result of LoadBitmapAsync function is a Task and you need to await its result before assigning it to the Source property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM