首页 > 解决方案 > 并行执行永无止境的多个任务

问题描述

我正在使用控制台 EXE,我必须连续下载特定数据,对其进行处理并将其结果保存在 MSSQL DB 中。

我将永无止境的任务用于创建单个任务,它适用于我的一种方法。我有 3 个同时执行的方法,所以我创建了 3 个要连续并行执行的任务,所以对代码进行了一些更改,这里是我的代码

CancellationTokenSource _cts = new CancellationTokenSource();
var parallelTask = new List<Task>
{
    new Task(
        () =>
        {
            while (!_cts.Token.WaitHandle.WaitOne(ExecutionLoopDelayMs))
            {
                DataCallBack(); // method 1
                ExecutionCore(_cts.Token);
            }
            _cts.Token.ThrowIfCancellationRequested();
         },
         _cts.Token,
         TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning),
     new Task(
         () =>
         {
             while (!_cts.Token.WaitHandle.WaitOne(ExecutionLoopDelayMs))
             {
                 EventCallBack(); // method 2
                 ExecutionCore(_cts.Token);
             }
             _cts.Token.ThrowIfCancellationRequested();
         },
         _cts.Token,
         TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning),
     new Task(
         () =>
         {
             while (!_cts.Token.WaitHandle.WaitOne(ExecutionLoopDelayMs))
             {
                 LogCallBack(); //method 3
                 ExecutionCore(_cts.Token);
             }
             _cts.Token.ThrowIfCancellationRequested();
         },
         _cts.Token,
         TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning)
};

Parallel.ForEach(parallelTask, task =>
{
    task.Start();
    task.ContinueWith(x =>
    {
        Trace.TraceError(x.Exception.InnerException.Message);
        Logger.Logs("Error: " + x.Exception.InnerException.Message);
        Console.WriteLine("Error: " + x.Exception.InnerException.Message);
    }, TaskContinuationOptions.OnlyOnFaulted);
});                

Console.ReadLine();

我想并行执行方法1、方法2和方法3。但是当我测试它时,只有 method3 正在执行
,我搜索了替代方法,但没有找到合适的指导。有没有适当的有效方法来做到这一点。

标签: c#multithreadingconsole-applicationtask-parallel-librarymultitasking

解决方案


不需要使用 Parallel.ForEach,因为您已经有 3 个任务。这应该这样做:

var actions = new Action[] { EventCallBack, LogCallBack, DataCallBack };

await Task.WhenAll(actions.Select(async action =>
{
    while (!_cts.Token.IsCancellationRequested)
    {
        action();
        ExecutionCore(_cts.Token);
        await Task.Delay(ExecutionLoopDelayMs, _cts.Token)
    }
}, _cts.Token));

推荐阅读