问题
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 aSystem.Threading.Tasks.Task
whose job is to enumerate theBlockingCollection
(usingGetConsumingEnumerable()
).
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()
theOnStart
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