任务在并行处理完成后立即重启

Task restart immediately after completion while parallel processing

我必须在完成相同任务后立即重新启动所有任务。请在下面查看我的程序;

class Program
    {
         static async Task Main(string[] args)
        {
            int _count = 1;
            while (true)
            {
                await ProcessTasksAsync();
                Console.Write("----Restart Tasks----" + (_count++).ToString() + Environment.NewLine);
                await Task.Delay(2000);
            }
        }

        static async Task ProcessTasksAsync()
        {
            Task<int> taskA = LongTaskA(10);
            Task<int> taskB = MediumTaskB(10);
            Task<int> taskC = ImmediateTaskC(10);

            var tasks = new[] { taskA, taskB, taskC };

            var processingTasks = tasks.Select(AwaitAndProcessAsync).ToList();
            await Task.WhenAll(processingTasks);
        }

        static async Task AwaitAndProcessAsync(Task<int> task)
        {
            var result = await task;
            Console.WriteLine("Return Result: " + result);
        }

        static async Task<int> LongTaskA(int _processingCount)
        {
            for (int i = 0; i < _processingCount; i++)
            {
                Console.Write(string.Format("LongTaskA:{0}", i.ToString()) + Environment.NewLine);
                await Task.Delay(7000);
            }
            return 1;
        }

        static async Task<int> MediumTaskB(int _processingCount)
        {
            for (int i = 0; i < _processingCount; i++)
            {
                Console.Write(string.Format("MediumTaskB:{0}", i.ToString()) + Environment.NewLine);
                await Task.Delay(3000);
            }
            return 2;
        }

        static async Task<int> ImmediateTaskC(int _processingCount)
        {
            for (int i = 0; i < _processingCount; i++)
            {
                Console.Write(string.Format("ImmediateTaskC:{0}", i.ToString()) + Environment.NewLine);
                await Task.Delay(1000);
            }
            return 3;
        }

    }

任务 A、B 和 C 并行运行。但是,即使完成某些任务也不会在完成后重新启动。当我使用“Whenall”时,它会等待完成其他任务。

我想在完成相同的任务后重新启动每个任务。我怎样才能做到这一点?

谢谢, 神女

您的程序目前 运行 同时执行这三个任务,(异步)等待它们全部完成,然后循环执行。

如果你想运行 每个任务循环,那么你只需移动循环:

static async Task ProcessTasksAsync()
{
  Task<int> taskA = LoopA(10);
  Task<int> taskB = LoopB(10);
  Task<int> taskC = LoopC(10);

  await Task.WhenAll(taskA, taskB, taskC);
}

static async Task LoopA()
{
  while (true)
    await AwaitAndProcessAsync(LongTaskA(10));
}

static async Task LoopB()
{
  while (true)
    await AwaitAndProcessAsync(MediumTaskB(10));
}

static async Task LoopC()
{
  while (true)
    await AwaitAndProcessAsync(ImmediateTaskC(10));
}