0

我有一个 Windows 服务,它每 20 秒唤醒一次并查看报告队列,并将根据报告队列中的内容执行程序。如果我独立运行报告程序,那么它可以正常工作。如果它是从服务执行的,我会在事件日志中收到以下错误...

Application: cqrAbandonedCallsRpt.exe 
    Framework Version: v4.0.30319 Description: 
        The process was terminated due to an unhandled exception. 
            Exception Info: System.TypeInitializationException Stack: at 
               CallQueueReport.cqrAbandonedCallsRpt.Main(System.String[]) 

日志中没有其他信息。我已经注释掉了 main 函数中的所有代码,但我仍然收到错误消息。该服务也在管理员帐户下运行。

知道什么会导致问题吗?

4

1 回答 1

2

It sounds like the problem isn't actually in the Main method but in the type initializer for the class which contains Main. Perhaps in a static field that gets initialized inline in the class? Something like this?:

class Program
{
    // this...
    static string someValue = SomeObject.FetchSomeValue();

    static void Main(string[] args)
    {
        // no code here
    }
}

The TypeInitializationException you're seeing is likely obscuring (possibly as an inner exception) the actual error that's taking place. Try removing all of the inline initialization code from the class and initializing values as a first step in Main(), then you can wrap the initialization code in a try/catch and log the actual error that's taking place, so you can meaningfully address the root cause.

(In my experience, TypeInitializationException is just a short way of saying ThereIsTooMuchUnvalidatedLogicAtTheClassLevelAndYouShouldPutItInAMethodException.)

于 2013-11-12T01:03:30.580 回答