Posted By

tomeddie78 on 12/10/12


Tagged


Versions (?)

Async Await Example


 / Published in: C#
 

A bit of example code that currently had a bug where the Debug.WriteLines that are "After FirstWait" and "After SecondWait" are never reached. What am I doing incorrectly?

  1. public void Main()
  2. {
  3. var result = LaunchTasks(new List<int>() { 5, 3 });
  4. Debug.WriteLine("The final result is {0}",result.Result);
  5. }
  6.  
  7. public async Task<bool> LaunchTasks(List<int> waitTimes)
  8. {
  9. bool result = false;
  10. List<Task> tasks = new List<Task>();
  11. try
  12. {
  13. foreach (int wait in waitTimes)
  14. {
  15. var task1 = FirstWait(wait);
  16. tasks.Add(task1);
  17. var task2 = SecondWait(wait);
  18. tasks.Add(task2);
  19. }
  20. Debug.WriteLine("About to await on {0} Tasks", tasks.Count);
  21. await Task.WhenAll(tasks);
  22. Debug.WriteLine("After WhenAll");
  23. }
  24. catch (Exception ex)
  25. {
  26. }
  27.  
  28. return result;
  29. }
  30.  
  31. private async Task<bool> FirstWait(int waitTime)
  32. {
  33. var task = Task.Factory.StartNew<bool>((delay) =>
  34. {
  35. try
  36. {
  37. int count = (int)delay;
  38. for (int i = 0; i < count; i++)
  39. {
  40. Debug.WriteLine("FirstWait is at {0}", i);
  41. }
  42. }
  43. catch (Exception ex)
  44. {
  45. Debug.WriteLine(ex.Message);
  46. }
  47.  
  48. return true;
  49. }, waitTime);
  50.  
  51. await Task.WhenAll(task);
  52. Debug.WriteLine("After FirstWait");
  53. return task.Result;
  54. }
  55.  
  56.  
  57. private async Task<bool> SecondWait(int waitTime)
  58. {
  59. var task = Task.Factory.StartNew<bool>((delay) =>
  60. {
  61. try
  62. {
  63. int count = (int)delay;
  64. for (int i = 0; i < count; i++)
  65. {
  66. Debug.WriteLine("SecondWait is at {0}", i);
  67. }
  68. }
  69. catch (Exception ex)
  70. {
  71. Debug.WriteLine(ex.Message);
  72. }
  73. return true;
  74. }, waitTime);
  75. await Task.WhenAll(task);
  76. Debug.WriteLine("After SecondWait");
  77. return task.Result;
  78. }

Report this snippet  

You need to login to post a comment.