【问题标题】:How to cancel a child task if parent times out?如果父超时,如何取消子任务?
【发布时间】:2013-08-27 14:10:52
【问题描述】:

以下代码同时运行 2 个任务,均设置了超时时间。

层级任务(父级)有一个总体超时值,当达到该值时,终止进程。

在 tier 任务中,许多节点任务(子任务)同步循环,因此任务 1 必须先完成,然后才能继续执行任务 2,依此类推。

如果某个子任务未能在某个时间范围内完成,则会超时并运行下一个子任务。

如果父任务超时,进程将停止,但当前未完成的子任务仍在后台运行。子任务是第三方网络服务,如果可能的话,我想终止它们以保持清洁。

我查看了 microsoft 示例,但正在努力使其与我自己的代码一起使用。

简而言之,如果父级终止,它只能通过超时或异常来完成,我需要取消当前在循环内运行的子级。

任何人都知道这是如何实现的。

public int NestedTask(IEnumerable<KeyValuePair<string, int>> nodes)
{
    int parentTimeout = 20 * 1000;
    int childTimeout = 2 * 1000;

        var tier = Task<int>.Factory.StartNew(() =>
        {
            foreach (var n in nodes)
            {
                var node = Task<int>.Factory.StartNew(() =>
                {
                    Thread.Sleep(n.Value * 1000);
                    return 1;
                });

                // If we get the result we return it, else we wait
                if (node.Wait(childTimeout))
                {
                    return node.Result;
                }
            }

            // return timeout node here;
            return -1;
        });

        if (!tier.Wait(parentTimeout))
        {
            // The child will continue on running though.
            ** CANCEL SINGLE CHILD ***
            return -2;
        }
        else if (tier.Exception != null)
        {
            // We have an error
        }

        return tier.Result;
    }

【问题讨论】:

  • 您的问题能否表述为“如何取消任务”?这似乎就是你想要的。
  • 见这里blogs.msdn.com/b/csharpfaq/archive/2010/07/19/…。简而言之,您必须向任务传递一个取消令牌并在其上调用取消。
  • @usr - 不止于此 - 需要识别子任务然后取消它。
  • 将任务的引用存储在以后可以检索的地方。此外,您无法取消 IO 任务。

标签: c# task-parallel-library task


【解决方案1】:

只需在子任务声明中指定 TaskCreationOptions.AttachedToParent 选项 (MSDN)。

var node = Task<int>.Factory.StartNew(() =>
{
    Thread.Sleep(n.Value * 1000);
    return 1;
}, TaskCreationOptions.AttachedToParent);

【讨论】:

    猜你喜欢
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2015-06-25
    • 1970-01-01
    • 2022-10-07
    • 2019-05-19
    相关资源
    最近更新 更多