The .Net article on Tasks shows two following two code snippets, one using await and the other using Task.Wait and says both are "functionally equivalent".
Isn't that technically incorrect then? Can someone please clarify?
Also if Tasks are supposed to be asynchronous and form the basis for Asynchronous Programming (TPL), why would ASP.Net allow a synchronous Wait on them anyway? Doesn't that kind of violate their main utility?
using System;
using System.Threading.Tasks;
public class Example
{
public static async Task Main()
{
await Task.Run( () => {
// Just loop.
int ctr = 0;
for (ctr = 0; ctr <= 1000000; ctr++)
{}
Console.WriteLine("Finished {0} loop iterations",
ctr);
} );
}
}
// The example displays the following output:
// Finished 1000001 loop iterations
using System;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
Task t = Task.Factory.StartNew( () => {
// Just loop.
int ctr = 0;
for (ctr = 0; ctr <= 1000000; ctr++)
{}
Console.WriteLine("Finished {0} loop iterations",
ctr);
} );
t.Wait();
}
}
// The example displays the following output:
// Finished 1000001 loop iterations
The article should explain the differences between the two calls clearly.
await XandTask.Run(...).Wait()are not equivalent as they do things vastly different, but in this case it doesn't matter.Mainmethod will be waited upon through code similar toMain().GetAwaiter().GetResult(), which is doing the same thing as.Wait(), it will block the calling thread until your task completes. So whether you write the code that blocks the thread while it waits, or you let the framework (or the compiler magic in the case of async Main) do it for you amounts to the same thing, the program main thread will block, waiting for your task to complete.