I'm trying to get my head around this and I think I know what's happenig, but just can't get something to work. I'd appreciate any help. Basically my demo code is to make a cup of coffee where I want the boil the kettle fuunction to run async as it takes a long time. I have put an await on MakeACupOfCoffee as I don't want the stopwatch timing until the entire process has finished. This is finishing early and I know why, but I've no idea how to make the code wait for the kettle to boil while allowing everything else to continue.
Thanks for any pointers.
Here's my code..
using System;
using System.Threading;
using System.Threading.Tasks;
namespace asyncawait
{
class Program
{
static void Main(string[] args)
{
TimeACoffee();
}
private static async Task TimeACoffee()
{
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
// MakeACupOfCoffee completes before WaitForTheKettleToBoil has finished,
// therefore the await doesn't behave as I want it to
await MakeACupOfCoffee();
stopwatch.Stop();
Console.WriteLine($"\n\nTime taken : {stopwatch.Elapsed}");
Console.ReadLine();
}
private static async Task MakeACupOfCoffee()
{
// This function shouldn't return until everything has completed
// I can't await here otherwise it'd be pointless doing asynchronously
WaitForTheKettleToBoil();
GetCup();
AddCoffee();
AddMilk();
AddSugar();
}
private static Task WaitForTheKettleToBoil()
{
return Task.Run(() =>
{
Console.WriteLine("Waiting for the kettle to boil...");
Thread.Sleep(8000);
});
}
private static void AddMilk()
{
Console.WriteLine("Adding milk");
Thread.Sleep(100);
}
private static void AddSugar()
{
Console.WriteLine("Adding sugar");
Thread.Sleep(100);
}
private static void GetCup()
{
Console.WriteLine("Getting cup");
Thread.Sleep(100);
}
private static void AddCoffee()
{
Console.WriteLine("Adding coffee");
Thread.Sleep(100);
}
}
}