fork download
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4.  
  5. class Program {
  6. public static int Add(int a, int b) {
  7. Console.WriteLine("Child thread starts");
  8. int result = a + b;
  9.  
  10. Console.WriteLine("Child thread goes to sleep");
  11. Thread.Sleep(5000); // the thread is paused for 5000 milliseconds
  12.  
  13. Console.WriteLine("Child thread resumes and finishes");
  14. return result;
  15. }
  16.  
  17. public static async Task<int> AddAsync(int a, int b)
  18. {
  19. int result = await Task.Run(() => Add(a, b));
  20. Console.WriteLine("Result computed = {0}", result);
  21. return result;
  22. }
  23.  
  24. public static void Main(string[] args) {
  25. int x = 30;
  26. int y = 12;
  27.  
  28. Console.WriteLine("Main thread starts");
  29. Task<int> task = AddAsync(x, y);
  30.  
  31. Console.WriteLine("Main thread waiting");
  32. int sum = task.Result;
  33. Console.WriteLine("Main thread finishes, sum = {0}", sum);
  34. }
  35. }
Success #stdin #stdout 0.04s 17532KB
stdin
Standard input is empty
stdout
Main thread starts
Child thread starts
Child thread goes to sleep
Main thread waiting
Child thread resumes and finishes
Result computed = 42
Main thread finishes, sum = 42