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:
- internal void Start ()
- {
- CancellationTokenSource token_source_01 = new CancellationTokenSource ();
- CancellationTokenSource token_source_02 = new CancellationTokenSource ();
- CancellationToken CToken_stop_waiting_01 = token_source_01.Token;
- CancellationToken CToken_stop_waiting_02 = token_source_02.Token;
- Task
- do_nothing_task_01 = Task.Run
- ( () =>
- {
- Console.WriteLine ("I am pretending to make a blocking call (#1).");
-
-
- Console.ReadLine();
- token_source_02.Cancel ();
- },
- CToken_stop_waiting_01
- );
- Task
- do_nothing_task_02 = Task.Run
- ( () =>
- {
- Console.WriteLine ("I am pretending to make a blocking call (#2).");
-
-
- Console.ReadLine();
- token_source_01.Cancel ();
- },
- CToken_stop_waiting_02
- );
- Thread.Sleep (TimeSpan.FromSeconds (10));
- Console.WriteLine ("This will not actually kill the task.");
- token_source_01.Cancel ();
- Thread.Sleep (TimeSpan.FromSeconds (10));
- token_source_02.Cancel ();
- try
- {
- do_nothing_task_01.Wait ();
- do_nothing_task_02.Wait ();
- }
- catch (TaskCanceledException xcpt)
- {
- Console.WriteLine($"{nameof(TaskCanceledException)} thrown with message: {xcpt.Message}");
- }
- catch (OperationCanceledException xcpt)
- {
- Console.WriteLine($"{nameof(OperationCanceledException)} thrown with message: {xcpt.Message}");
- }
- finally
- {
- V_token_source.Dispose();
- }
- Console.WriteLine (" *** END");
- Console.ReadLine();
- }
THANKS!