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);
}
Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. Note: Even though the return value of an async function behaves as if it's wrapped in a Promise.resolve , they are not equivalent.
The simplest way to execute a method asynchronously is to start executing the method by calling the delegate's BeginInvoke method, do some work on the main thread, and then call the delegate's EndInvoke method. EndInvoke might block the calling thread because it does not return until the asynchronous call completes.
Use the Result property on the asynchronous Task, like so: // Synchronous method. void Method()
You can call methods asynchronously in four different ways using the BeginInvoke() and EndInvoke() methods of the Delegate class. The four different ways are using the EndInvoke pattern, WaitHandle, Polling pattern and using a Callback Pattern.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With