如果失败则重新启动任务

时间:2017-05-18 09:36:59

标签: c# task continuations

如果失败,我正在尝试重启其中一个任务。我使用.ContinueWith(t => { HandleException(t); }, TaskContinuationOptions.OnlyOnFaulted); HandleException(t)方法应该在激发任务的数组中找到任务并在其位置创建一个新任务。只有传递给我HandleException(t)方法的任务与原始任务不同,所以我无法在我的激活任务中找到它。此外,在处理异常时,仍然存在执行任务。

实施例:

using System;
using System.Threading.Tasks;
using System.Threading;

static Task[] tasks;
static void Main(string[] args)
{
    tasks = new Task[2];
    for (int i = 0; i < tasks.Count(); i++)
    {
        tasks[i] = Task.Run(() => { Thread.Sleep(1000); throw new Exception("BOOM"); })
             .ContinueWith(t => { HandleException(t); }
             , TaskContinuationOptions.OnlyOnFaulted);

        Console.WriteLine(String.Format("Task {0} started", tasks[i].Id));
    }

    Console.ReadLine();
}

static void HandleException(Task task)
{
    Console.WriteLine(String.Format("Task {0} stopped", task.Id));

    // Check task status
    for (int i = 0; i < tasks.Count(); i++)
    {
        Console.WriteLine(String.Format("Task {0} status = {1}", i, tasks[i].Status));
    }
    // fFind and restart the task here
    if (tasks.Contains(task))
    {
        int index = Array.IndexOf(tasks, task);
        tasks[index] = Task.Run(() => { Thread.Sleep(1000); throw new Exception("BOOM"); })
         .ContinueWith(t => { HandleException(t); }
         , TaskContinuationOptions.OnlyOnFaulted);

        Console.WriteLine(String.Format("Task {0} started", tasks[index].Id));
    }
}

我的申请结果如下:

Task 3 started
Task 6 started
Task 5 stopped
Task 0 status = Running
Task 2 stopped
Task 1 status = Running
Task 0 status = Running
Task 1 status = Running

由于传递给HandleException(t)的任务与原始任务不同,因此在tasks[]中找不到该任务,因此未重新启动。同时查看tasks[]的状态还没有停止。如何正确重启我的任务?

1 个答案:

答案 0 :(得分:4)

那是因为你在数组中存储了continuation任务,而不是原始任务(即存储ContinueWith的结果)。要修复,请改为存储原始任务:

var task = Task.Run(() => { Thread.Sleep(1000); throw new Exception("BOOM");});
task.ContinueWith(t => { HandleException(t); }
         , TaskContinuationOptions.OnlyOnFaulted);
tasks[i] = task;