如何在任何异常时保持 ActionBlock 运行

How to keep ActionBlock running on any exception

我有一个 ActionBlock 可以简单地连续处理来自无限循环的消息。在 ActionBlock 内,我创建了一个 http post。当出现任何与网络相关的错误时,该方法会抛出异常并且块为 faulted/stopped。这不是我想要的行为。即使发生异常,我也希望处理运行。 (继续打Process方法)模拟我的程序;

private static ExecutionDataflowBlockOptions processBlockOptions
{
    get
    {
        return new ExecutionDataflowBlockOptions
        {
            MaxDegreeOfParallelism = 1
        };
    }
}

static async Start()
{
    processQueue = new 
        ActionBlock<QueueMessage>(
            async (item) =>
            {
                await Process(item);
            },
            processBlockOptions); 

    while (!Stopped)
    {
       //Read from DB and do logic with item
       QueueMessage item= new QueueMessage();
       await processQueue.SendAsync(item);                              
    }
}    

private async static Task<int> Process(QueueMessage item)
{
    try
    {
        await item.HttpPost(order);
    }
    catch (Exception ex)
    {
        //Http endpoint might be broken
        throw ex;
    }
}

您正在重新抛出异常,但您做错了:

throw ex;

如果您需要记录错误或暂时停止管道,您不需要抛出任何东西,只需记录 ex.ToString() 并做出相应的反应。第二件事是你应该使用 throw; 而不是 throw ex;,因为你正在为异常重写堆栈跟踪,这在这种情况下并不重要,但在更复杂的工作流程的情况下可能会产生误导.