What is the difference between Task and async Task?

2

In the code below I wrote two methods, one with Task return and another async Task . What happens differently in the execution of these methods since for one I added in the construction the reserved word await and in the other not.

public static async Task Main(string[] args)
{            
    var result = await KmToMiles(1d);
    Console.WriteLine("Km to miles: {0}", result);
    Console.ReadLine();
}

public static async Task<double> KmToMiles(double value)
{
    Console.WriteLine(nameof(KmToMiles));
    await Task.Delay(1000);
    return value * 0.621371;
}

public static Task<double> KmToMiles(double value)
{
    Console.WriteLine(nameof(KmToMiles));
    Task.Delay(1000);
    return Task.FromResult<double>(value * 0.621371);
}
    
asked by anonymous 09.08.2018 / 16:53

1 answer

4

When you use a async you are allowing the method to run asynchronously as another method. Asynchronous methods always return nothing or return a task that will work in the future, so we use some type Task , it's the one that knows how to manage it.

Generally returning a Task without a async does not help much because we encapsulate the return on a task that can not be asynchronous. The only reason to do this is to have an intermediate method that needs to receive asynchronous information from another method and pass on. Note that at this point there is no asynchronicity, which in itself is not a problem if used correctly. This method will be blocking but if it is in a location this does not matter can be useful. Unable to do this would have to code "languages" that would probably have more of a responsibility. But remember that it is blocking.

In your example the second method will not execute asynchronously returning the encapsulated result. usually this is wrong because async is good with IO and not with processing. In an example, the end will be the same as the first one lets other things run during delay and the second will not allow this, the difference is async , which in the first compels the use of Task , and in the second, using this way does not make much sense except to make calls compatible since using a await expects a task and not the gross value. Just remembering that this code only makes sense if each method is in a different namespace and only one of them is imported at the time of the call, which in practice makes it of little advantage to have this compatibility because to exchange the implementation has that tinkering with the code in any way, and requiring to review all of it may even be beneficial.

    
09.08.2018 / 17:16