循环内的嵌套任务 [英] Nested task inside loop

查看:24
本文介绍了循环内的嵌套任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在循环中实现嵌套任务 - 这是我目前的模式,但是我不确定,因为这是我第一次使用并行任务库.

I'm trying to implement a nested task inside a loop - this is the pattern I have so far, however I'm far from sure as this is the first time I've used the parallel task library.

父(层)任务应该等待子(节点)任务完成.

The parent (tier) task should wait for the children (node) tasks to complete.

    public int NestedTask(IEnumerable<MatchTier> tierNodes)
    {
        var tier = Task<int>.Factory.StartNew(() =>
        {
            Task<int> node = null;

            foreach(var n in tierNodes)
            {
                node = Task<int>.Factory.StartNew(() =>
                {
                    // Task logic goes here

                    return 1; // temp placeholder
                });

                // if a valid value is returned then exit this loop
            }

            return node.Result;

        });

        return tier.Result;
    }

子节点循环直到返回第一个有效值,然后退出循环,将有效值传递给父节点.

The child nodes loop until the first valid value is returned, then the loop should be exited, passing the valid value to the parent.

子节点和父节点也都需要超时.每个子节点将被允许运行大约 3 秒,之后该进程将超时并询问下一个节点.

Both the child and parent nodes require a timeout too. Each child will be allowed approx 3 seconds to run after which the process will be timed out and the next node interrogated.

父进程的总体超时值约为 15 - 20 秒,之后,如果没有收到有效响应,它也应该终止.

the parent has an overall timeout value of approx 15 - 20 seconds, after which, if no valid response has been recieved, it too should terminate.

这看起来合乎逻辑吗?

推荐答案

如前所述 task.Wait()task.Result(等待并抓取结果)和 Task.WaitAll(theTaskCollection) 是执行此操作的方法.我已经稍微改变了你的实现来解决这个问题,但我非常不确定你真正想要返回什么.我删除了外部任务,因为它似乎不需要.

As stated task.Wait(), task.Result (wait and grab result) and Task.WaitAll(theTaskCollection) are the ways to do this. I've changed your implementation slightly to account for that but I'm very unsure of what you really want to return. The outer task I removed since it didn't seem to be needed.

public int NestedTask(IEnumerable<MatchTier> tierNodes)
{
  var tasks = tierNodes.Select(node => Task<int>.Factory.StartNew(() =>
            {
                // Task logic goes here
                return 1; // temp placeholder
            })).ToList(); // Enumerate to start tasks, not doing this would case WaitAll to start them one at a time (i believe)

  if (!Task.WaitAll(tasks, timeOutInMilliseconds))
    // Handle timeout...

  return tasks.First().Result; // Is this what you want?
}

添加修改后的解决方案.

Adding modified solution.

public int NestedTask(IEnumerable<string> tierNodes)
{
  int parentTimeout = 15 * 1000;
  int childTimeout = 3 * 1000;

  var tier = Task<int>.Factory.StartNew(() =>
  {
      foreach (var n in tierNodes)
      {
          var node = Task<int>.Factory.StartNew(() =>
          {
              // Task logic goes here
              return 1;
          });

          // If we get the result we return it, else we wait
          if (node.Wait(childTimeout))
              return node.Result;
      }
      throw new Exception("did not get result!");
  });

  if (!tier.Wait(parentTimeout))
  {
      // The child will continue on running though.
      throw new TimeoutException("parent timed out");
  }
  else if (tier.Exception != null)
  {
      // We have an error
      throw tier.Exception.InnerException;
  }

  return tier.Result;
}

这篇关于循环内的嵌套任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆