博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
分享一个异步任务在遇到IO异常时支持递归回调的辅助方法
阅读量:6990 次
发布时间:2019-06-27

本文共 3649 字,大约阅读时间需要 12 分钟。

public void TryAsyncActionRecursively
( string asyncActionName, Func
> asyncAction, Action
mainAction, Action
successAction, Func
getContextInfoFunc, Action
failedAction, int retryTimes) where TAsyncResult : AsyncOperationResult{ var retryAction = new Action
(currentRetryTimes => { if (currentRetryTimes >= _immediatelyRetryTimes) { Task.Factory.StartDelayedTask(_retryIntervalForIOException, () => mainAction(currentRetryTimes + 1)); } else { mainAction(currentRetryTimes + 1); } }); var executeFailedAction = new Action
(ex => { try { if (failedAction != null) { failedAction(ex); } } catch (Exception unknownEx) { _logger.Error(string.Format("Failed to execute the failedCallbackAction of asyncAction:{0}, contextInfo:{1}", asyncActionName, getContextInfoFunc()), unknownEx); } }); var processTaskException = new Action
((ex, currentRetryTimes) => { if (ex is IOException) { _logger.Error(string.Format("Async task '{0}' has io exception, contextInfo:{1}, current retryTimes:{2}", asyncActionName, getContextInfoFunc(), currentRetryTimes), ex); retryAction(retryTimes); } else { _logger.Error(string.Format("Async task '{0}' has unknown exception, contextInfo:{1}, current retryTimes:{2}", asyncActionName, getContextInfoFunc(), currentRetryTimes), ex); executeFailedAction(ex); } }); var completeAction = new Action
>(t => { if (t.Exception != null) { processTaskException(t.Exception.InnerException, retryTimes); return; } if (t.IsCanceled) { _logger.ErrorFormat("Async task '{0}' was cancelled, contextInfo:{1}, current retryTimes:{2}", asyncActionName, getContextInfoFunc(), retryTimes); retryAction(retryTimes); return; } var result = t.Result; if (result.Status == AsyncOperationResultStatus.IOException) { _logger.ErrorFormat("Async task '{0}' has io exception, contextInfo:{1}, current retryTimes:{2}, errorMsg:{3}", asyncActionName, getContextInfoFunc(), retryTimes, result.ErrorMessage); retryAction(retryTimes); return; } if (successAction != null) { successAction(result); } }); try { asyncAction().ContinueWith(completeAction); } catch (IOException ex) { _logger.Error(string.Format("Execute async action '{0}' failed, contextInfo:{1}, current retryTimes:{2}", asyncActionName, getContextInfoFunc(), retryTimes), ex); retryAction(retryTimes); } catch (Exception ex) { _logger.Error(string.Format("Execute async action '{0}' failed, contextInfo:{1}, current retryTimes:{2}", asyncActionName, getContextInfoFunc(), retryTimes), ex); executeFailedAction(ex); }}

该函数的功能是:执行一个异步任务(返回Task的方法),如果执行出现IO异常,则重试当前主函数(mainAction);用户的mainAction中会再次调用TryAsyncActionRecursively方法。从而实现当遇到IO异常时,能做到不断重试。另外,重试只立即重试指定的次数,超过指定次数,则不立即重试,而是暂停一定间隔后再次执行。该函数还提供当acyncAction执行成功或失败后的回调函数,以及允许传入当前上下文的一些说明信息,以便记录有意义的错误日志信息。

下面是使用示例:

private void PublishEventAsync(ProcessingCommand processingCommand, EventStream eventStream, int retryTimes){    TryAsyncActionRecursively
("PublishEventAsync", () => _eventPublisher.PublishAsync(eventStream), currentRetryTimes => PublishEventAsync(processingCommand, eventStream, currentRetryTimes), result => { _logger.DebugFormat("Publish events success, {0}", eventStream); processingCommand.Complete(new CommandResult(CommandStatus.Success, processingCommand.Command.Id)); }, () => string.Format("[eventStream:{0}]", eventStream), ex => processingCommand.Complete(new CommandResult(CommandStatus.Failed, processingCommand.Command.Id)), retryTimes);}
PublishEventAsync(processingCommand, eventStream, 0);

转载地址:http://ufkvl.baihongyu.com/

你可能感兴趣的文章
python/python读取excel
查看>>
顾客如何成为上帝?品牌的全域数据中心+精细化的运营
查看>>
C#实现邮件发送
查看>>
bind主从配置
查看>>
Spring从入门到精通(一)----IoC(控制反转)
查看>>
Fedora9建立交叉编译环境
查看>>
关于MySQL的在线扩容
查看>>
Void类的用法
查看>>
【shell 】syntax error in conditional expression
查看>>
写的还不错的专题,android性能优化
查看>>
expdp 报The value (30) of MAXTRANS parameter ignored错误的原因诊断
查看>>
百度地图之基础地图
查看>>
SAS中的cmiss函数
查看>>
快速查看LINUX 系统硬件的脚本
查看>>
上下文切换与多线程实现的代价
查看>>
Hadoop数据传输工具sqoop
查看>>
[UI] 精美UI界面欣赏[3]
查看>>
2015 CALLED THE INTERFACE OF 2014
查看>>
通过IEnumerable和IDisposable实现可暂停和取消的任务队列
查看>>
Yii 框架学习--02 进阶
查看>>