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 void Main(string[] args) {
  18. int x = 30;
  19. int y = 12;
  20.  
  21. Task<int> task = new Task<int>(() => Add(x, y));
  22. Console.WriteLine("Main thread starts");
  23. task.Start();
  24.  
  25. Console.WriteLine("Main thread waiting");
  26. int sum = task.Result;
  27. Console.WriteLine("Main thread finishes, sum = {0}", sum);
  28. }
  29. }
Success #stdin #stdout 0.02s 332480KB
stdin
Standard input is empty
stdout
Main thread starts
Main thread waiting
Child thread starts
Child thread goes to sleep
Child thread resumes and finishes
Main thread finishes, sum = 42