首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何中止/取消TPL任务?

如何中止/取消TPL任务?
EN

Stack Overflow用户
提问于 2011-01-24 23:42:17
回答 8查看 173.6K关注 0票数 161

在线程中,我创建一些System.Threading.Task并启动每个任务。

当我执行.Abort()来终止线程时,任务不会中止。

如何将.Abort()传输到我的任务?

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 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();
    }
}
票数 238
EN

Stack Overflow用户

发布于 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类来确定是否应该取消它。

票数 34
EN

Stack Overflow用户

发布于 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
    }
}

虽然它可以工作,但不推荐使用这种方法。如果你能控制在任务中执行的代码,你最好去适当地处理取消。

票数 32
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4783865

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档