【问题标题】:How to continue with other tasks in the queue if current fails?如果当前失败,如何继续队列中的其他任务?
【发布时间】:2012-12-28 10:15:06
【问题描述】:

我有一些代码可以执行如下所示的队列

Queue
    .GetConsumingEnumerable()
    .ToObservable()
    .Select(x => x.ObserveOn(NewThreadScheduler.Default))
    .SubscribeOn(NewThreadScheduler.Default)
    .Subscribe(
        grp => grp.ForEachAsync(b => b.Execute())
                  .ContinueWith(ExecuteOnTaskFailure, TaskContinuationOptions.OnlyOnFaulted));

ExecuteOnTaskFailure方法定义如下

private static void ExecuteOnTaskFailure(Task previousTask)
{
    if (!previousTask.IsFaulted)
        return;

    if (previousTask.Exception != null && previousTask.Exception.InnerExceptions != null)
        foreach (var exception in previousTask.Exception.InnerExceptions)
        {
            Logger.Error("Task failed continued to the next task : " + exception.Message, exception);
        }
}

这不起作用。我似乎无法弄清楚如何使队列中的任务继续执行,即使其中一个任务无法执行。还有办法让我在队列末尾重新排队这个失败的任务吗?

非常感谢这里的任何帮助。

【问题讨论】:

    标签: c# multithreading task-parallel-library system.reactive producer-consumer


    【解决方案1】:

    听起来你想要的是循环中的try-catch

    grp.ForEachAsync(async b =>
    {
        try
        {
            await b.Execute();
        }
        catch (Exception ex)
        {
            Logger.Error(ex);
            Queue.Add(b);
        }
    })
    

    但是BlockingCollection 对异步不太友好,因为它在为空时会阻塞(顾名思义)。您可能需要考虑另一种方法。

    【讨论】:

    • + 1 表示回复并尝试捕捉!我最终这样做了,没有时间更新这篇文章。
    猜你喜欢
    • 2017-01-30
    • 1970-01-01
    • 2011-07-20
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多