R Burton

R Burton

  • NA
  • 2
  • 595

Killing a Task the Proper Way

Sep 22 2020 4:44 PM
HI Everybody,
 
Here is the scenario: Suppose that I have two tasks that are making blocking calls to services that are taking a long time to respond.
 
One gets done before the other, so I want that task to kill the others.
 
I know that using abort is bad and evil, so what would be a good way to make this work?
 
This is my test code:
  1. internal void Start ()  
  2. {  
  3. CancellationTokenSource token_source_01 = new CancellationTokenSource ();  
  4. CancellationTokenSource token_source_02 = new CancellationTokenSource ();  
  5. CancellationToken CToken_stop_waiting_01 = token_source_01.Token;  
  6. CancellationToken CToken_stop_waiting_02 = token_source_02.Token;  
  7. Task  
  8. do_nothing_task_01 = Task.Run  
  9. ( () =>  
  10. {  
  11. Console.WriteLine ("I am pretending to make a blocking call (#1).");  
  12. // Pretend that this ReadLine is a call to a service  
  13. // that takes a long time to complete.  
  14. Console.ReadLine();  
  15. token_source_02.Cancel ();  
  16. },  
  17. CToken_stop_waiting_01  
  18. );  
  19. Task  
  20. do_nothing_task_02 = Task.Run  
  21. ( () =>  
  22. {  
  23. Console.WriteLine ("I am pretending to make a blocking call (#2).");  
  24. // Pretend that this ReadLine is a call to a service  
  25. // that takes a long time to complete.  
  26. Console.ReadLine();  
  27. token_source_01.Cancel ();  
  28. },  
  29. CToken_stop_waiting_02  
  30. );  
  31. Thread.Sleep (TimeSpan.FromSeconds (10));  
  32. Console.WriteLine ("This will not actually kill the task.");  
  33. token_source_01.Cancel ();  
  34. Thread.Sleep (TimeSpan.FromSeconds (10));  
  35. token_source_02.Cancel ();  
  36. try  
  37. {  
  38. do_nothing_task_01.Wait ();  
  39. do_nothing_task_02.Wait ();  
  40. }  
  41. catch (TaskCanceledException xcpt)  
  42. {  
  43. Console.WriteLine($"{nameof(TaskCanceledException)} thrown with message: {xcpt.Message}");  
  44. }  
  45. catch (OperationCanceledException xcpt)  
  46. {  
  47. Console.WriteLine($"{nameof(OperationCanceledException)} thrown with message: {xcpt.Message}");  
  48. }  
  49. finally  
  50. {  
  51. V_token_source.Dispose();  
  52. }  
  53. Console.WriteLine (" *** END");  
  54. Console.ReadLine();  
  55. }  
THANKS!