我的场景:
- Windows 服务 .NET 4
- 我轮询数据库中的实体。
- 当新实体进来时,它们会被添加到
BlockingCollection
.
- 在服务的
OnStart
我创建一个System.Threading.Tasks.Task
他的工作是枚举BlockingCollection
(using GetConsumingEnumerable()
).
我遇到的问题是这样的:
- 当任务中发生未处理的异常时,我希望记录异常并停止服务。
- 除非我调用,否则我无法捕获任务的异常
Task.Wait()
.
- 如果我打电话
Task.Wait()
the OnStart
方法阻塞并且服务永远不会完成启动。
那么我怎样才能做到这一点呢?
您可以使用“.ContinueWith”方法处理任务中的异常:
Task.Factory.StartNew(() => {
// Do some long action
Thread.SpinWait(5000000);
// that eventually has an error :-(
throw new Exception("Something really bad happened in the task.");
// I'm not sure how much `TaskCreationOptions.LongRunning` helps, but it sounds
// like it makes sense to use it in your situation.
}, TaskCreationOptions.LongRunning).ContinueWith(task => {
var exception = task.Exception;
/* Log the exception */
}, TaskContinuationOptions.OnlyOnFaulted); // Only run the continuation if there was an error in the original task.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)