fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4.  
  5. public class AgeIncrementor
  6. {
  7. private static readonly object syncLock = new object();
  8. public AgeIncrementor()
  9. {
  10. Age = 0;
  11. }
  12.  
  13. public int Age { get; set; }
  14. public Task IncrementAge()
  15. {
  16. return Task.Run(() =>
  17. {
  18. try
  19. {
  20. lock (syncLock)
  21. {
  22. Age += 10;
  23. Console.WriteLine("Increased to {0}", Age);
  24. }
  25. }
  26. catch (Exception ex)
  27. {
  28. Console.WriteLine(ex.Message);
  29. }
  30. });
  31.  
  32. }
  33. public void Complete()
  34. {
  35. Console.WriteLine("Printing from Complete() method.");
  36. }
  37.  
  38. static void Main(string[] args)
  39. {
  40.  
  41. var ageIncrementor = new AgeIncrementor();
  42. Console.WriteLine("Age is {0}", ageIncrementor.Age);
  43. List<Task> tasks = new List<Task>();
  44. for (int i = 0; i < 5; i++)
  45. {
  46. tasks.Add(ageIncrementor.IncrementAge());
  47. }
  48. Task.WaitAll(tasks.ToArray());
  49. ageIncrementor.Complete();
  50. Console.WriteLine("Completed");
  51. Console.WriteLine("Final Age is {0}", ageIncrementor.Age);
  52. Console.ReadKey();
  53. }
  54. }
Success #stdin #stdout 0.01s 265024KB
stdin
Standard input is empty
stdout
Age is 0
Increased to 10
Increased to 20
Increased to 30
Increased to 40
Increased to 50
Printing from Complete() method.
Completed
Final Age is 50