How can I roll my own async awaitable methods?
I see that writing an async method is easy as pie in some cases:
private async Task TestGeo() { Geolocator geo = new Geolocator(); Geoposition pos = await geo.GetGeopositionAsync(); double dLat = pos.Coordinate.Latitude; double dLong = pos.Coordinate.Latitude; }
...but sadly also see that not just any method can be made async willy-nilly, though; to wit: this doesn't work:
private async Task TestAsyncAwait() { int i = await TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5); }
...it stops me with the compile error, "Cannot await int"; a hint at design time similarly tells me, "type 'int' is not awaitable"
I also tried this with the same results:
Task<int> i = await TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5);
What must I do to make my methods awaitable?
As Linebacker and S. Cleary indicated (any relation to that cat who used to be on KNBR?), this works:
int i = await Task.Run(() => TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5));
...that is to say, it compiles -- but it never "moves."
At runtime, it tells me I should "await" the CALL to TestAsyncAwait(), but if I do that, it doesn't compile at all...
You can use await Task. Yield(); in an asynchronous method to force the method to complete asynchronously. Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.
The await keyword in C# programming language is used to suspend all async methods enclosed until the point where the operations presented by the asynchronous method are completed. In order or a developer to call multiple functions in an asynchronous way, async and await are highly used and recommended.
If a method has no async operations inside it there's no benefit in making it async . You should only have async methods where you have an async operation (I/O, DB, etc.). If your application has a lot of these I/O methods and they spread throughout your code base, that's not a bad thing.
You only need to return an awaitable. Task
/Task<TResult>
is a common choice; Task
s can be created using Task.Run
(to execute code on a background thread) or TaskCompletionSource<T>
(to wrap an asynchronous event).
Read the Task-Based Asynchronous Pattern for more information.
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