What should I do to make my methods accessible?

How can I run my own asynchronous expected methods?

I see that writing an asynchronous method in some cases is as easy as pie:

private async Task TestGeo() { Geolocator geo = new Geolocator(); Geoposition pos = await geo.GetGeopositionAsync(); double dLat = pos.Coordinate.Latitude; double dLong = pos.Coordinate.Latitude; } 

... but, unfortunately, it is also clear that not every method can be made asynchronously by will or not; for wit: this does not work:

 private async Task TestAsyncAwait() { int i = await TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5); } 

... it stops me with a compilation error: "Can't wait for int"; the development time hint also tells me: "The type" int "is not expected"

I also tried this with the same results:

  Task<int> i = await TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5); 

What should I do to make my methods accessible?

UPDATE

As pointed out by Linebacker and S. Cleary (any relation to this cat that used to be on KNBR?), This works:

 int i = await Task.Run(() => TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5)); 

... that is, it compiles, but it never "moves."

At runtime, it tells me that I have to β€œwait” CALL for TestAsyncAwait (), but if I do, it will not compile at all ...

+42
c # windows-8 windows-store-apps async-await
Nov 22 '12 at 18:56
source share
4 answers

You only need to return while waiting. Task / Task<TResult> is a common choice; Task can be created using Task.Run (to execute code in the background thread) or TaskCompletionSource<T> (to wrap an asynchronous event).

For more information, read the Task-Based Asynchronous Template .

+26
Nov 22 '12 at 19:53
source share
β€” -

Your method

 private async Task TestAsyncAwait() { int i = await TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5); } 

should be written as follows

 private async Task TestAsyncAwait() { Task<int> t = new Task<int>(() => { return TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5); }); t.Start(); await t; } 

If you need to return int, replace the task type:

 private async Task<int> TestAsyncAwait() { Task<int> t = new Task<int>(() => { return TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5); }); t.Start(); return await t; } 

Additional explanation here .

+15
Jun 04 '15 at 17:24
source share
 var something = Task<int>.Factory.StartNew(() => 0); something.Wait(); int number = something.Result; 
+2
Mar 11
source share

You need to either use the expected return or return a Task<Type of await call>

  •  private async Task<Geoposition> TestGeo() { Geolocator geo = new Geolocator(); return await geo.GetGeopositionAsync(); } 
  •  private async Task<int> TestAsyncAwait() { return await TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5); } 
+1
Nov 22
source share



All Articles