Problems with windows service, blockingcollection, and Multithreading

筅森魡賤 提交于 2019-12-10 21:09:44

问题


My scenario:

  • Windows Service .NET 4
  • I poll a database for entities.
  • When new entities come in they are added to a BlockingCollection.
  • In the service's OnStart I create a System.Threading.Tasks.Task whose job is to enumerate the BlockingCollection (using GetConsumingEnumerable()).

The problem I'm having is this:

  • When an unhandled exception occurs in the task, I want the exception logged and the service stopped.
  • I can't catch exceptions from the task unless I call Task.Wait().
  • If I call Task.Wait() the OnStart method blocks and the service never finishes starting.

So how can I make this work?


回答1:


You can handle exceptions in a task using the `.ContinueWith' method:

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.


来源:https://stackoverflow.com/questions/7770291/problems-with-windows-service-blockingcollection-and-multithreading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!