class Program
{
static void Main(string[] args)
{
var p = new Program();
p.Run();
}
void Run()
{
var task = CalculatePiAsync();
task.Wait();
}
async Task CalculatePiAsync()
{
var task = new Task(CalculatePi);
task.Start();
await task;
}
void CalculatePi()
{
Thread.Sleep(2000);
}
}
// with comments and logging
class Program
{
static void Main(string[] args)
{
var p = new Program();
p.Run();
}
// this method runs synchronously, because it does not call await
void Run()
{
Log($"Run() - begin");
var task = CalculatePiAsync();
// force a blocking wait to prevent console app exit
Log($"Run() - waiting");
task.Wait();
Log($"Run() - end");
}
// async method
async Task CalculatePiAsync()
{
Log($"CalculatePiAsync() - begin");
var task = new Task(CalculatePi);
task.Start();
// 'await' does NOT block the program thread
// Execution of this method IS suspended until after CalculatePi completes, but this 'soft block' is managed
// by the C# generated async state machine via a method callback.
// When the task completes, the line after await task will execute.
await task;
Log($"CalculatePiAsync() - end");
}
void CalculatePi()
{
Log("CalculatePi() - begin");
Thread.Sleep(2000);
Log($"CalculatePi() - end");
}
void Log(string message)
{
Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}: {message}");
}
1: Run() - begin
1: CalculatePiAsync() - begin
3: CalculatePi() - begin
1: Run() - waiting
3: CalculatePi() - end
3: CalculatePiAsync() - end
1: Run() - end