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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…