【问题标题】:Problems with windows service, blockingcollection, and MultithreadingWindows 服务、blockingcollection 和多线程的问题
【发布时间】:2011-12-07 21:21:32
【问题描述】:

我的场景:

  • Windows 服务 .NET 4
  • 我在数据库中轮询实体。
  • 当新实体进入时,它们会被添加到BlockingCollection
  • 在服务的OnStart 中,我创建了一个System.Threading.Tasks.Task,其工作是枚举BlockingCollection(使用GetConsumingEnumerable())。

我遇到的问题是这样的:

  • 当任务中发生未处理的异常时,我希望记录异常并停止服务。
  • 除非我调用Task.Wait(),否则我无法从任务中捕获异常。
  • 如果我调用Task.Wait() OnStart 方法阻塞并且服务永远不会完成启动。

那么我怎样才能做到这一点呢?

【问题讨论】:

  • 不能在Task body中捕获所有异常并适当处理吗?
  • 无法处理出乎意料的事情。

标签: .net multithreading exception-handling windows-services task-parallel-library


【解决方案1】:

您可以使用 `.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.

【讨论】:

  • 谢谢!这就是我一直在寻找的。​​span>
  • 新手在原型应用程序中尝试上述代码示例的注意事项:使用变量创建任务-`Task myTask = ; myTask.Wait();` myTask.Wait() 将导致主线程等待创建的任务,以便您可以看到上述操作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多