如何在任何异常情况下保持 ActionBlock 运行

ibu*_*ubi 2 c# task task-parallel-library async-await tpl-dataflow

我有一个ActionBlock简单地处理来自无限循环的消息。在里面ActionBlock我做了一个http post。当发生任何与网络相关的错误时,该方法会抛出异常并且该块会出现故障/停止。这不是我想要的行为。即使发生异常,我也希望处理运行。(继续打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;
    }
}
Run Code Online (Sandbox Code Playgroud)

VMA*_*Atm 6

你重新抛出异常,但你做错了:

throw ex;
Run Code Online (Sandbox Code Playgroud)

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