C# 单元测试并行编程

C# 单元测试并行编程,c#,unit-testing,parallel.foreach,C#,Unit Testing,Parallel.foreach,我有一个模拟执行各种任务的工具 代码如下所示: while (true) { tasks.ForEachWithIndex((item, index) => { if (tasksToExecute[index] == null || tasksToExecute[index].ShouldRerun()) { tasksToExecute[index] = System.Threading.Tasks.Task.Factory.StartN

我有一个模拟执行各种任务的工具

代码如下所示:

while (true)
{
    tasks.ForEachWithIndex((item, index) =>
    {
        if (tasksToExecute[index] == null || tasksToExecute[index].ShouldRerun())
        { tasksToExecute[index] = System.Threading.Tasks.Task.Factory.StartNewRecurring(() => ScheduledTaskHelper.ExecutePlatformTask(logWriter, uow, item)); }
    });

    // The tasks have been added to the factory, so let's start them now.
    var handleTaskCompletionTask = System.Threading.Tasks.Task.WhenAny(tasksToExecute.ToArray()).ContinueWith(
        (completedTask, o) =>
        {
            var taskId = completedTask.Result.Id;
            tasksToExecute.Find(x => x.Id == taskId).Rerun(true);
        }, null);

    try { handleTaskCompletionTask.Wait(); }
    catch (Exception ex)
    { }
}
注意:我不会发布所有的实现细节,因为这将花费我们很多时间

让我们假设我有两个任务,然后系统接受这两个任务并并行处理它们。当其中一个任务完成时,通过将其添加到并行循环中再次对其进行重新处理

但现在我正在努力研究如何对这个实现进行单元测试。 我在考虑以下方法:

创建两个任务:

  • 1运行30秒的任务
  • 1个运行5秒的任务
检查1秒后,两个任务的状态是否均为正在运行。 检查15秒后,两个任务的状态是否仍为正在运行


我希望有人能帮我解决这个问题。

你到底有什么问题?你不知道要写哪些单元测试?我知道我想写什么。我想检查所有任务在指定的时间后是否都处于运行状态。所以我的意思是,即使任务完成了,也需要重新开始。但我不知道如何将其转换为单个单元测试。由于您不能重新运行任务,您将如何检查任务是否“重新运行”?一旦重新运行方法执行,它将创建一个新任务,而旧任务将处于已完成状态,因此您的“外部”引用将被废弃?那么除了使该单元可测试之外,您还有什么建议?也许使用线程而不是任务,或者这是一种糟糕的方法?