using System.Threading.Tasks;
using System.Diagnostics;
private static Stopwatch _stopwatch = new Stopwatch();
public static void Main()
MakeBreakfastAsync().GetAwaiter().GetResult();
public static void MakeBreakfastSync()
Console.WriteLine("\n============================");
Console.WriteLine("\nMakeBreakfastSync\n");
Console.WriteLine("\nNOTE: The number before the time is current threadId\n");
WriteLog("MakeBreakfastSync Start");
WriteLog("MakeBreakfastSync End");
Console.WriteLine($"\nTotal time: {_stopwatch.Elapsed.TotalMilliseconds}ms\n");
private static void StartTimer()
private static void BoilCoffee()
WriteLog("BoilCoffee Start");
WriteLog("BoilCoffee End");
private static void ToastBread()
WriteLog("ToastBread Start");
WriteLog("ToastBread End");
private static void FryEggs()
WriteLog("FryEggs Start");
public static void WriteLog(string text)
string message = Thread.CurrentThread.ManagedThreadId + " " + _stopwatch.Elapsed.ToString(@"mm\:ss\.fff").PadRight(12) + text;
Console.WriteLine(message);
public static async Task MakeBreakfastAsync()
Console.WriteLine("\n============================");
Console.WriteLine("\nMakeBreakfastAsync");
Console.WriteLine("\nNOTE: tasks maybe using different threads provided by ThreadPool, but unlike parallel programming, it is only one thread at a time\n");
WriteLog("MakeBreakfastAsync Start");
Task boilCoffeeTask = BoilCoffeeAsync();
Task toastBreadTask = ToastBreadAsync();
Task fryEggsTask = FryEggsAsync();
WriteLog("MakeBreakfastAsync End");
Console.WriteLine($"\nTotal time: {_stopwatch.Elapsed.TotalMilliseconds}ms\n");
private static async Task BoilCoffeeAsync()
WriteLog("BoilCoffeeAsync Start");
WriteLog("BoilCoffeeAsync End");
private static async Task ToastBreadAsync()
WriteLog("ToastBreadAsync Start");
WriteLog("ToastBreadAsync End");
private static async Task FryEggsAsync()
WriteLog("FryEggsAsync Start");
WriteLog("FryEggsAsync End");
public static void MakeBreakfastParallel()
Console.WriteLine("\n============================");
Console.WriteLine("\nMakeBreakfastParallel\n");
Console.WriteLine("Available processors: " + Environment.ProcessorCount + "\n");
var parallelOptions = new ParallelOptions
MaxDegreeOfParallelism = useProcessors
Console.WriteLine("Using processors: " + useProcessors + "\n");
WriteLog("MakeBreakfastParallel Start");
Parallel.Invoke(parallelOptions,
Console.WriteLine("\nMakeBreakfastParallel End\n");
Console.WriteLine($"\nTotal time: {_stopwatch.Elapsed.TotalMilliseconds}ms\n");