TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
R Burton
NA
2
589
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:
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)."
);
// Pretend that this ReadLine is a call to a service
// that takes a long time to complete.
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)."
);
// Pretend that this ReadLine is a call to a service
// that takes a long time to complete.
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!
Reply
Answers (
0
)
To call video file in wpf web browser
bind treeview from json using C#