c# - 并行执行永无止境的多个任务
问题描述
我正在使用控制台 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 正在执行
,我搜索了替代方法,但没有找到合适的指导。有没有适当的有效方法来做到这一点。
解决方案
不需要使用 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));
推荐阅读
- java - Spring MVC - 更改页面时丢失数据
- ruby-on-rails - 没有路线匹配 [POST] "/users/1"
- php - 变量不会通过 URL 传递给 PHP
- ui-automation - 为什么我必须在 Windows 上运行自动化测试用例?
- javascript - 有没有办法重新定义 Javascript charCodeAt 和 fromCharCode 从函数中调用的标准 Ascii 字符集?
- python-3.x - 如何根据 AUC 指标在 Keras 中保存最佳模型?
- ios - 如何从 iOS 10 及更低版本的 WKWebView 获取 cookie?
- c# - ASP.Net Core MVC - 部分视图的身份验证上下文不同?
- android - IIS 和 Apache Content-Type 标头... IIS 只接受一个,Apache 接受多个
- python - 如何在数据框 python 中使用时间戳查找值