.net windows服务、blockingcollection和多线程问题

.net windows服务、blockingcollection和多线程问题,.net,multithreading,exception-handling,windows-services,task-parallel-library,.net,Multithreading,Exception Handling,Windows Services,Task Parallel Library,我的设想: Windows服务.NET 4 我轮询数据库中的实体 当新实体进入时,它们被添加到BlockingCollection 在服务的OnStart中,我创建了一个System.Threading.Tasks.Task,其任务是枚举BlockingCollection(使用GetConsumingEnumerable()) 我遇到的问题是: 当任务中发生未处理的异常时,我希望记录异常并停止服务 除非调用task.Wait(),否则无法捕获任务中的异常 如果调用Task.Wait()方

我的设想:

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

  • 当任务中发生未处理的异常时,我希望记录异常并停止服务
  • 除非调用
    task.Wait()
    ,否则无法捕获任务中的异常
  • 如果调用
    Task.Wait()
    方法,则
    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.

您不能捕获任务体中的所有异常并适当地处理它们吗?无法处理您不期望的事情。谢谢!这就是我一直在寻找的。请注意,对于在原型应用程序中尝试上述代码示例的新手:使用变量创建任务-`task myTask=;myTask.Wait();`Wait()将导致主线程等待创建的任务,以便您可以看到上面的操作