What is the difference between Task and async Task?

Asked

Viewed 533 times

4

In the code below I wrote two methods, one with the return Task and another async Task. What happens differently in the execution of these methods since for one added in the construction the reserved word awaitand 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);
}
  • 1

    I think the difference, basically, is that one is synchronous (Task) and the other asynchronous (async Task).

  • 1

    Take a look here https://answall.com/questions/123173/diff%C3%A7a-entre-task-e-thread

1 answer

5


When you use a async is allowing the method to be executed asynchronously with another method. Asynchronous methods always return nothing or return a task that will result in the future, so we use some kind Task, is she who knows how to manage it.

In general return a Task without a async It doesn’t help much because we encapsulate the return in a task that can’t 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 it 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 that does not matter it may be useful. Without being able to do this you would have to make codes "linguistics" that would probably have more than one responsibility. But remember that it is blocking.

In your example the second method will only not run asynchronously by returning the encapsulated result. Usually this is wrong because async is good with IO and not with processing. For example the end will be the same only that the first lets other things run during the delay and the second will not allow it, the difference is the async, which in the first requires the use of Task, and in the second, using this way does not make much sense except to compatibilize the calls 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 one namespace different and only one of them is imported at the time of the call, which in practice makes it hardly advantageous to have this compatibility because to change the implementation has to tamper with the code anyway, and require reviewing all it can be beneficial.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.