在线程中,我创建一些System.Threading.Task
并启动每个任务。
当我执行.Abort()
来终止线程时,任务不会中止。
如何将.Abort()
传输到我的任务?
发布于 2011-01-24 23:44:53
不能。任务使用线程池中的后台线程。此外,不建议使用Abort方法取消线程。您可以查看following blog post,它解释了使用取消令牌取消任务的正确方法。下面是一个例子:
class Program
{
static void Main()
{
var ts = new CancellationTokenSource();
CancellationToken ct = ts.Token;
Task.Factory.StartNew(() =>
{
while (true)
{
// do some heavy work here
Thread.Sleep(100);
if (ct.IsCancellationRequested)
{
// another thread decided to cancel
Console.WriteLine("task canceled");
break;
}
}
}, ct);
// Simulate waiting 3s for the task to complete
Thread.Sleep(3000);
// Can't wait anymore => cancel this task
ts.Cancel();
Console.ReadLine();
}
}
发布于 2013-02-07 05:19:04
如果捕获在其中运行任务的线程,则很容易中止任务。以下是演示这一点的示例代码:
void Main()
{
Thread thread = null;
Task t = Task.Run(() =>
{
//Capture the thread
thread = Thread.CurrentThread;
//Simulate work (usually from 3rd party code)
Thread.Sleep(1000);
//If you comment out thread.Abort(), then this will be displayed
Console.WriteLine("Task finished!");
});
//This is needed in the example to avoid thread being still NULL
Thread.Sleep(10);
//Cancel the task by aborting the thread
thread.Abort();
}
我使用Task.Run()展示了最常见的用例-使用任务的舒适与旧的单线程代码,它不使用CancellationTokenSource类来确定是否应该取消它。
发布于 2013-10-11 14:26:20
就像this post建议的那样,这可以通过以下方式完成:
int Foo(CancellationToken token)
{
Thread t = Thread.CurrentThread;
using (token.Register(t.Abort))
{
// compute-bound work here
}
}
虽然它可以工作,但不推荐使用这种方法。如果你能控制在任务中执行的代码,你最好去适当地处理取消。
https://stackoverflow.com/questions/4783865
复制相似问题