For some tutorial I'm planning to explain async and await using some callbacks. Based on https://learn.microsoft.com/dotnet/csharp/programming-guide/concepts/async I tried to implement something similar using callbacks:
static void Main(string[] args)
{
Console.WriteLine("Lets start a delicious breakfast");
FryEggsCallback(2, () =>
{
Console.WriteLine("eggs are ready");
});
FryBaconCallback(3, () =>
{
Console.WriteLine("bacon is ready");
});
ToastBreadCallback(2, x =>
{
ApplyButter(x);
ApplyJam(x);
Console.WriteLine("toast is ready");
});
Console.WriteLine("Breakfast is ready!");
}
static void FryEggsCallback(int count, Action onReady)
{
Task.Delay(3000).Wait(); // simulate some work that should be done
onReady();
}
static void FryBaconCallback(int count, Action onReady)
{
Task.Delay(3000).Wait();
onReady();
}
static void ToastBreadCallback(int count, Action<Toast> onReady)
{
Task.Delay(3000).Wait();
onReady(new Toast());
}
However the Task.Delay().Wait() blocks my thread, so instead of having the three calls running asynchronously, they run sequentially one by one.
How would I go about implementing the three calls asynchronously with callbacks instead of using async and await?
Task.Delay(3000).ContinueWith(task => onReady());?`async/awaitisn't callbacks. Instead of explaining it, you'll confuse people. Withasync/awaitawaiting inside a loop is no different than awaiting outside it. With just callbacks, it's a nightmareasync/await. A Task is neither a thread nor a function. It's a promise that something will complete and maybe produce a value in the future. That promise may execute in a threadpool thread, it may represent an IO operation that will be signaled by the OS on completion, or it may be signaled by a timer or another thread.awaitworks on that promise, not the original call. You could say that the code afterawaitis a callback on that Promiseasync/awaitwork. The key abstraction, the Promise, is missing from callbacks. In .NET Framework 4, beforeasync/awaitwere introduced, people used continuations withContinueWiththat called delegates when the Promise/Task completed. You can consider that code as a callback to the Promise