How does Task become an int?

后端 未结 2 1242
醉梦人生
醉梦人生 2020-11-28 17:53

We have this method:

async Task AccessTheWebAsync()
{ 
    HttpClient client = new HttpClient();

   Task getStringTask = client.Get         


        
2条回答
  •  春和景丽
    2020-11-28 18:45

    Does an implicit conversion occur between Task<> and int?

    Nope. This is just part of how async/await works.

    Any method declared as async has to have a return type of:

    • void (avoid if possible)
    • Task (no result beyond notification of completion/failure)
    • Task (for a logical result of type T in an async manner)

    The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length - you can't make the method just return int, as the actual method will return when it hits the first await expression which hasn't already completed. So instead, it returns a Task which will complete when the async method itself completes.

    Note that await does the opposite - it unwraps a Task to a T value, which is how this line works:

    string urlContents = await getStringTask;
    

    ... but of course it unwraps it asynchronously, whereas just using Result would block until the task had completed. (await can unwrap other types which implement the awaitable pattern, but Task is the one you're likely to use most often.)

    This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:

    public async Task AccessTheWebAndDoubleAsync()
    {
        var task = AccessTheWebAsync();
        int result = await task;
        return result * 2;
    }
    

    (Or simply return await AccessTheWebAsync() * 2; of course.)

提交回复
热议问题