等待任务完成

时间:2020-04-15 16:52:39

标签: c# async-await windows-services task

我正在粘贴我编写的Windows服务片段。 为了完成任务,我将默认服务终止时间更改为30分钟。

       private static void TaskMethod1()
       {
          //I am doing a bunch of operations here, all of them can be replaced with a sleep for 25 minutes
       }

       private static async Task TaskMethod()
       {
           while(runningService)
           {
              // Thi will create more than one task in parallel to run and each task can take upto 30 minutes to finish
              Task.Run(() => TaskMethod1(arg1);
           }
       }
       internal static void Start()
        {
            runningService = true;
            Task1 = Task.Run(() => TaskMethod());
        }

        internal static void Stop()
        {
            runningService = false;
            Task1.Wait();
        }

在上面的代码中,我编写了Task1.wait(),它等待task1完成,但不等待TaskMethod中创建的所有任务,即执行TaskMethod1的任务。 我有以下问题:

  1. 如何使服务等待使用Task.Run(() => TaskMethod1(arg1);创建的任务。(请注意,为Task.Run(() => TaskMethod1(arg1);创建的任务可能不止一个,但是Task1 = Task.Run(() => TaskMethod());仅运行一次。)
  2. 我运行Task1.wait()时为什么不等待作为该任务一部分创建的所有任务?

1 个答案:

答案 0 :(得分:1)

  1. 您必须跟踪创建的任务,以便以后引用它们。例如:
private static List<Task> _taskList = new List<Task>();

private static void TaskMethod()
{
   while(runningService)
   {
      // This will create more than one task in parallel to run and each task can take upto 30 minutes to finish
      _taskList.Add(Task.Run(() => TaskMethod1(arg1)));
   }
}

internal static void Stop()
{
    runningService = false;
    Task.WaitAll(_taskList.ToArray());
    Task1.Wait();
}
  1. 因为Task1不依赖于其他任务的完成。在TaskMethod()中,您只是创建Task并继续前进。那里什么也没有告诉它等待任何东西。除非您在await返回的.Wait()TaskTask.Run,否则您的代码将继续运行,而不会依赖于刚创建的Task

这是我在您的代码中看到的一个问题。您的while(runningService)循环将以您的CPU允许的最快速度循环,在几秒钟内创建数千个新任务。您确定那是您想要的吗?

也许您希望它在循环内等待完成,然后再循环并开始一个新的循环?如果我是正确的,那么您的循环应如下所示:

private static async Task TaskMethod()
{
   while(runningService)
   {
      // This will create more than one task in parallel to run and each task can take upto 30 minutes to finish
      await Task.Run(() => TaskMethod1(arg1));
   }
}

但这一次只能创建一个Task