ibubi
ibubi

Reputation: 2539

How to keep ActionBlock running on any exception

I have an ActionBlock that simply processes messages that comes from an infinite loop continuously. Inside ActionBlock I make an http post. When on any network related error, the method throws exception and the block is faulted/stopped. This is not the behavior that I want. I want processing runs even though exception occurs. (Keep hitting Process method) To simulate my program;

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;
    }
}

Upvotes: 2

Views: 881

Answers (1)

VMAtm
VMAtm

Reputation: 28355

You're re-throwing your exceptions, and you're doing it wrong:

throw ex;

If you need to log the errors or stop the pipeline for a while, you don't need to throw anything, simply log ex.ToString() and react accordingly. Second thing is that you should use throw; instead of throw ex;, as you're rewriting the stack trace for exception, which doesn't really matter in this case but can be misleading in case of more complicated workflow.

Upvotes: 6

Related Questions