I have to process items off a queue.

Deleting items off the queue is a manual call to Queue.DeleteMessage. This needs to occurs regardless of whether or not the processing succeeds.

var queueMessage = Queue.GetMessage();

try
{
    pipeline.Process(queueMessage);
}
catch (Exception ex)
{
    try
    {
        Logger.LogException(ex);
    }
    catch { }
}
finally
{
    Queue.DeleteMessage(queueMessage);
}

Problem:

On failure, I log the error to some data store. If this logging fails (perhaps the data store is not available), I still need the message to be deleted from the queue.

I have wrapped the LogException call in another try catch. Is this the correct way or performing thing?

有帮助吗?

解决方案

Following code is enough. finally blocks execute even when exception is thrown in catch block.

var queueMessage = Queue.GetMessage();    
try
{
    pipeline.Process(queueMessage);
}
catch (Exception ex)
{
    Logger.LogException(ex);
}
finally
{
    Queue.DeleteMessage(queueMessage);//Will be executed for sure*
}

其他提示

The finally block always executes, even if it throws an unhandled error (unless it end the app). So yes.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top