Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What must I do to make my methods awaitable?

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?

UPDATE

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...

like image 561
B. Clay Shannon-B. Crow Raven Avatar asked Nov 22 '12 18:11

B. Clay Shannon-B. Crow Raven


People also ask

How do you make a method async?

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.

What is Awaitable in C#?

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.

Should all methods be async?

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.


1 Answers

You only need to return an awaitable. Task/Task<TResult> is a common choice; Tasks 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.

like image 114
Stephen Cleary Avatar answered Oct 05 '22 22:10

Stephen Cleary