在我的应用程序中,当任务超过预设超时时,我需要强制停止任务。直到我看到我只能通过令牌取消线程,但线程仍然会在后台运行。即使我在超时后抛出异常,线程也会继续运行......
有代码和结果示例:
internal class Program
{
private static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
var cls = new CancellationTokenSource();
Task task = Task.Factory.StartNew(state =>
{
Console.WriteLine("Task Started" );
Timer timer = new Timer(TimeElapsed, cls, 3000, 0);
Thread.Sleep(6000);
Console.WriteLine("End Task");
}, cls.Token);
}
Console.ReadLine();
}
private static void TimeElapsed(object obj)
{
try
{
var cls = (CancellationTokenSource)obj;
cls.Cancel();
cls.Token.ThrowIfCancellationRequested();
}
catch (Exception)
{
Console.WriteLine("Aborted");
}
}
}