并行执行永无止境的多任务

时间:2019-12-06 10:45:16

标签: c# multithreading console-application task-parallel-library multitasking

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

我参考Never ending Task来创建单个任务,它对我来说只有一种方法。 我有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正在执行
我搜索了替代方法,但没有找到合适的指导。有什么合适的有效方法可以做到这一点。

1 个答案:

答案 0 :(得分:1)

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

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));
相关问题