Search code examples
c#.netwindows-runtimeasync-awaitasync-ctp

Recommended method signature when returning output from asynchronous method?


I have one asynchronous method:

public async Task<BitmapSource> GetBitmapAsync(double[] pixels);

Let's say I also have this class:

public class PixelData
{
    public double[] Pixels { get; }
}

I now want to create a convenience method producing a BitmapSource output, using the asynchronous method above to do the work. I can come up with at least three approaches to do this, but it is not immediately obvious to me which one I should choose from an efficiency and reliability point of view.

Can someone advice; what are the advantages and drawbacks of each one of the following approaches?

Option A Create a synchronous method that returns the Result of the Task:

public BitmapSource GetBitmap(PixelData pixelData)
{
    return GetBitmapAsync(pixelData.Pixels).Result;
}

Option B Create a synchronous (or is it asynchronous?) method that returns Task<BitmapSource>:

public Task<BitmapSource> GetBitmap(PixelData pixelData)
{
    return GetBitmapAsync(pixelData.Pixels);
}

Option C Create an asynchronous method that explicitly uses await:

public async Task<BitmapSource> GetBitmapAsync(PixelData pixelData)
{
    return await GetBitmapAsync(pixelData.Pixels);
}

Solution

  • I think you're over-thinking this.

    You've got a method that returns a type that happens to be a Task<T>. You want a method that takes a different type of parameter and passes through to the original method. So Option B is fine:

    public Task<BitmapSource> GetBitmap(PixelData pixelData)
    {
        return GetBitmapAsync(pixelData.Pixels);
    }
    

    The method should be called GetBitmapAsync though.

    Option A would be the way to expose a synchronous ( blocking ) version of the method.

    Option C doesn't actually achieve anything more than Option B.