并行执行永不结束的多重任务

问题描述 投票:0回答:1

我正在控制台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我搜索了替代方法,但没有找到合适的指导。有没有适当的有效方法可以做到这一点。

c# multithreading console-application task-parallel-library multitasking
1个回答
0
投票
由于您已经有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));

© www.soinside.com 2019 - 2024. All rights reserved.