Below we have a synchronous method that counts to 5.
static void Main(string[] args)
{
Console.WriteLine("START");
Count();
Console.WriteLine("END");
Console.ReadKey();
}
private static void Count()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i + 1);
}
Console.WriteLine("End of count");
}
Output
START 1 2 3 4 5 End of count END
But some times we don't want to stop the code execution to make something, like counting.
In the next examples are shown how the code execution is affected by await
, async
, Task.Run()
and .Wait()
.
static void Main(string[] args)
{
Console.WriteLine("START");
CountAsync();
Console.WriteLine("END");
Console.ReadKey();
}
private static async Task CountAsync()
{
Task.Run(() => {
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i + 1);
}
});
Console.WriteLine("End of count");
}
Output
START End of count END 1 2 3 4 5
static void Main(string[] args)
{
Console.WriteLine("START");
CountAsync();
Console.WriteLine("END");
Console.ReadKey();
}
private static async Task CountAsync()
{
await Task.Run(() => {
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i + 1);
}
});
Console.WriteLine("End of count");
}
Output
START END 1 2 3 4 5 End of count
static void Main(string[] args)
{
Console.WriteLine("START");
CountAsync().Wait();
Console.WriteLine("END");
Console.ReadKey();
}
private static async Task CountAsync()
{
await Task.Run(() => {
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i + 1);
}
});
Console.WriteLine("End of count");
}
Output
START 1 2 3 4 5 End of count END