What must I do to make my methods awaitable?

44,436

Solution 1

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.

Solution 2

Your method

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

should be written like this

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 the 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;
}

Solution 3

var something = Task<int>.Factory.StartNew(() => 0);
something.Wait();
int number = something.Result;

Solution 4

You need to either consume the awaited return or return Task<Type of await call>

  1. private async Task<Geoposition> TestGeo()
    {
        Geolocator geo = new Geolocator();
        return await geo.GetGeopositionAsync();
    }
    
  2. private async Task<int> TestAsyncAwait()
    {
        return await TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5);
    }
    
Share:
44,436

Related videos on Youtube

B. Clay Shannon-B. Crow Raven
Author by

B. Clay Shannon-B. Crow Raven

My novel about climate change and social justice featuring talking animals traveling through time and space to prevent disasters is now available on amazon, in three formats: Taterskin &amp; The Eco Defenders Kindle eBook; Taterskin &amp; The Eco Defenders Paperback; Taterskin &amp; The Eco Defenders Hardcover Taterskin &amp; The Eco Defenders, told in “first canine” by the titular character, a Labrador Retriever, is the story of a few humans and several talking animals who travel through time and space to make the past—and thus the future—a better place. The improvements effected by the Eco Defenders benefit not just the earth itself, but also mistreated humans and animals. In Book 1 (“Wonders Never Cease”), The Eco Defenders travel 150 million years into the past, to meet a Pterodactyl and make plans to “nip Nazism in the bud.” After that, it's on to 1787 Australia to protect the indigenous people and the environment there. The Eco Defenders next go to India, where they assemble animals from all over that country to put an end to Thuggee and fights to the death between Cobras and Mongooses. Their final stop is 1885 Africa, where the Eco Defenders band together with the local animals to prevent King Leopold of Belgium from taking control of the Congo, following which they put an end to the poaching of animals throughout the continent. Book 2 (“Tell it to Future Generations”) takes up with the Eco Defenders following up on their earlier adventures by 1) Preventing the American Civil War in 1861, after which a slave they free joins them; 2) Saving the Indians from being massacred at Wounded Knee in 1890, following which Chapawee, a Sioux Indian, joins the Eco Defenders; 3) Putting an end to the practice of vivisection (experimentation on live animals) in 1903; 4) Coming to the aid of exploited workers in 1911 Manhattan, saving hundreds from the Triangle Shirtwaist Fire; and 5) Traveling to the Amazon Basin in 1978 to protect and preserve the Amazon rainforest. @@@@@@@@@@@@@@@@@@@@@@@ I have lived in eight states; besides my native California (where I was born and where I now again reside), in chronological order I have infested: New York (Brooklyn), Montana (Helena), Alaska (Anchorage), Oklahoma (Bethany), Wisconsin (New Berlin and Oconomowoc), Idaho (Coeur d'Alene), and Missouri (Piedmont). I am a writer of both fiction (for which I use the nom de guerre "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006 and can be downloaded gratis here.

Updated on July 09, 2022

Comments

  • B. Clay Shannon-B. Crow Raven
    B. Clay Shannon-B. Crow Raven almost 2 years

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

    • L.B
      L.B over 11 years
      int i = await Task.Run(() => TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5));
    • Christian
      Christian over 11 years
      I recommend you read TAP
    • B. Clay Shannon-B. Crow Raven
      B. Clay Shannon-B. Crow Raven over 11 years
      So Lambdas are not just de rigeur, but obligatory now? I've viewed them, at least up to now, as clever-clever tricks.
    • Stephen Cleary
      Stephen Cleary over 11 years
      Are you sure you want to make this awaitable?
    • B. Clay Shannon-B. Crow Raven
      B. Clay Shannon-B. Crow Raven over 11 years
      No, I'm just experimenting - I want to know how to make methods awaitable so that I can "do it until the cows come home" or "without even thinking (much) about it" when I need to.
  • Jeson Martajaya
    Jeson Martajaya almost 9 years
    The question is about #2, and for #2, the error says "Type 'int' is not awaitable"
  • aaronburro
    aaronburro almost 8 years
    Downvoted because the OP is clearly trying to do this asynchronously
  • philologon
    philologon over 7 years
    Thanks to aaronburro for adding a downvote explanation. This is too rare.
  • Denis G. Labrecque
    Denis G. Labrecque almost 4 years
    The link is dead
  • Marcelo Scofano Diniz
    Marcelo Scofano Diniz over 2 years
    Rare and useful.