与Windows服务,blockingcollection和多线程问题 [英] Problems with windows service, blockingcollection, and Multithreading
本文介绍了与Windows服务,blockingcollection和多线程问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的情况:
- 在Windows服务.NET 4
- 我轮询实体的数据库。
- 在当前新的实体进来,他们被添加到
BlockingCollection
。 - 在该服务的
的OnStart
创建一个System.Threading.Tasks.Task
他的工作就是枚举BlockingCollection
(使用GetConsumingEnumerable()
)。
- 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:
- 在当前未处理的异常的任务时,我想除了记录和服务已停止。
- 我无法从任务捕获异常,除非我称之为
Task.Wait()
。 - 如果我称之为
Task.Wait()
的的OnStart
方法块和服务永远不会完成启动。
- 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?
推荐答案
您可以处理使用`.ContinueWith'的方法在任务异常:
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.
这篇关于与Windows服务,blockingcollection和多线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文