Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

c# - Canceling a task

I have a task which i need to cancel if the wait time is over. For instance

var t = Task.Factory.StartNew(() => 
{
  Thread.Sleep(5000) // some long running task
  "do something"
});
Task.WaitAll(new[] {t}, 1000);

But it seems the task still keeps working. I tried using CancellationTokenSource but that didnt seem to work as well.

I confirmed this using the following snippet

static void Main(string[] args)
        {
            var cancellationTokenSource = new CancellationTokenSource();

            var t = Task.Factory.StartNew(() => {
                Thread.Sleep(5000);
                Console.WriteLine("Still working");
            }, cancellationTokenSource.Token);

            Task.WaitAll(new[] {t}, 1000);

            cancellationTokenSource.Cancel();

            Console.ReadLine();
        }

Console displays "Still working". I thought the task would have been cancelled.

I am sure I am missing something. What am i missing? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Cancellation tokens don't magically cancel anything. They just allow you to check for cancellation in a standardized way, e.g. via ThrowIfCancellationRequested.

So typically you'd have some task which needs to perform a lot of work. It periodically calls ThrowIfCancellationRequested, and then any code which needs to cancel the task will call Cancel on the CancellationTokenSource when it needs to. The task will throw when it next checks for cancellation, and all will be well.

It sounds like you're looking for a non-cooperative cancellation - and that would be dangerous, for exactly the same reasons that the normal Thread.Abort is dangerous. It's cleaner to let the task pick the points at which it will allow itself to be cancelled.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...