简体   繁体   中英

How to create an async method that can return the non-void value?

I try to write a class with method that uses some awaitable operations. This condition makes me define this method as async. But I can't return non-void value from this method. BitmapImage in my case. Here's the code

public sealed class Thumbnailer
{
    public async BitmapImage GetThumbImageFromFile(StorageFile sourceFile)
    {
        StorageItemThumbnail thumb = await sourceFile.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView, 600, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);
        IRandomAccessStream thumbStream = thumb;
        BitmapImage thumbPict = new BitmapImage();
        thumbPict.SetSource(thumbStream);
        return thumbPict;
    }
}

How to fix this?

But I can't return non-void value from this method

Yes you can, but it has to be Task or Task<T> for some T . So you can change your method to:

public async Task<BitmapImage> GetThumbImageFromFile(StorageFile sourceFile)

The whole nature of an async method is that you call it, and control will (usually) return to the caller before the whole of the body of the method has completed - so a task is returned to indicate the promise of a result being available later on . By the time control returns to the caller, there is no BitmapImage to return. With the task, the caller can fetch the image when it is available. (Often async methods are called by other async methods, allowing you to await the task returned to get the value, of course.)

It's difficult to describe async succinctly in the space of a Stack Overflow answer, but I suggest you go back and read up on async/await again from scratch - it's important that you understand its fundamental nature before going too far. The MSDN async page is a good starting point.

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