下面是我的Windows服务代码。当我调试代码时,我得到错误/异常:

CSMessageUtility的类型初始化式。CSDetails抛出了一个异常。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using CSMessageUtility;

namespace CS_Data_Trasmmiting_Service
{
    public partial class svcCSWinServ : ServiceBase
    {
        //private string sLogFormat;
        //private string sErrorTime;
        private Thread new_thread;
        Logger logObject = new Logger();
        private bool isenable = true;

        public svcCSWinServ()
        {
            InitializeComponent();
            logObject.append("Initialize Service " + DateTime.Now.ToString(), 70);
            CheckForAlarms();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                new_thread = new Thread(new ThreadStart(CheckForAlarms));
                new_thread.Start();
            }
            catch
            {
            }

            logObject.append("Service Started successfully " + DateTime.Now.ToString(), 70);
        }

        protected override void OnStop()
        {
            try
            {
                isenable = false;
                new_thread.Abort();
            }
            catch
            {

            }
            logObject.append("Service Stopped successfully " + DateTime.Now.ToString(), 70);
        }


        void CheckForAlarms()
        {
            try
            {
                while (true)
                {
                    //if((DateTime.Now.ToString("HH:mm") == "18:00"))
                    //{

                        logObject.append("Start Sending Data " +DateTime.Now.ToString(), 70);
                        try
                        {
                            //SendAllInfo();
                            string str = CSMessageUtility.CSDetails.createDHSMessageFormat();
                            Thread.Sleep(2000);
                            string str1 = CSMessageUtility.CSDetails.createEALMessageFormat();
                            Thread.Sleep(2000);
                            string str2 = CSMessageUtility.CSDetails.createProductStatusMessageForamt();
                            Thread.Sleep(2000);
                            string str3 = CSMessageUtility.CSDetails.createEODMessageFormat();
                            Thread.Sleep(2000);
                            string str4 = CSDetails.createProductReceiptEntryatBOSMessageFormat();
                            Thread.Sleep(2000);
                            string str5 = CSMessageUtility.CSDetails.createProductSaleMessageFormat();
                            Thread.Sleep(2000);
                            string str6 = CSMessageUtility.CSDetails.createTotalizerExceptionMessageFormat();
                            Thread.Sleep(2000);
                            //CSMessageUtility.CSDetails.createDailyCOtransferMessageFormat();
                            //Thread.Sleep(2000);

                        }
                        catch (Exception ee)
                        {
                            logObject.append(ee.Message, 70);
                        }
                        logObject.append("Finished Sending Data " +DateTime.Now.ToString(), 70);
                        Thread.Sleep(3000);
                    //}
                    //Thread.Sleep(20000);
                }
            }
            catch (Exception ex)
            {
                logObject.append("Thread Exception: "+ ex.Message + " "+ DateTime.Now.ToString(), 70);

                try
                {
                    new_thread.Abort();
                }
                catch (Exception ex1)
                {
                    logObject.append("Thread Exception: " +ex1.Message + " " + DateTime.Now.ToString(), 70);
                }

                if (isenable == true)
                {
                    new_thread = new Thread(new ThreadStart(CheckForAlarms));
                    new_thread.Start();
                }
            }
        }
    }
}

当前回答

错误提示类型/类初始化失败。这通常发生在类的构造函数中出现异常时。最常见的原因是您在从配置文件读取的构造函数中赋了一些值,而配置文件缺少这些值。

其他回答

检查TypeInitializationException的InnerException属性;它可能包含有关潜在问题的信息,以及问题发生的确切位置。

字典键应该是唯一的!

在我的例子中,我正在使用一个字典,我发现其中有两个项目偶然有相同的键。

Dictionary<string, string> myDictionary = new Dictionary<string, string>() {
            {"KEY1", "V1"},
            {"KEY1", "V2" },
            {"KEY3", "V3"},
        };

In my case, I had a helper class that was static. In that class was a method to initialize a SqlCommand dependent on variables. As this was being called in several places I moved it to the helper class and called as needed, so this method was also static. Now I had a global property that was the connection string in Global.asax pointing to the connection string in web.config. Intermittently I would get "The type initializer for 'Helper' threw an exception". If I moved the method from the Helper class to the class where it was being called from all was good. The inner exception complained of the object being null (Helper class). What I did was add Using Helper to Global.asax and even though it was not being used by Global.asax this solved the problem.

类似穆罕默德·伊克巴尔所说的…我在一个VB。NET(也可能是c#)项目,其中我从App.config中删除了一个键值对,它由一个全局变量引用到模块Main的Sub Main()。因此,异常(和break)在子Main()之前发生在Module Main中。如果我在Dim上有断点就好了,但我们通常不会在全局变量上中断。也许一个很好的理由不声明全局引用App.config?换句话说,这个…

类型为“System”的未处理异常。在未知模块中发生TypeInitializationException'。 命名空间的类型初始化式。Main'抛出了一个异常。

是由……

App.config

<connectionStrings>
    <!--<add name="ConnectionString1" connectionString="..." />-->

主模块

Module Main
    Dim cnnString As String = ConfigurationManager.ConnectionStrings("ConnectionString1")  '<-- BREAK HERE (EXCEPTION)

    Sub Main()

        // main code

    End Main
End Module

另一种可能导致这种情况的情况是,当你有一段代码调用:

string sParam = **ConfigurationManager.AppSettings["SOME_PARAM"].ToString();

请记住,必须使用OWSTIMER.EXE.CONFIG文件进行配置文件设置。我有一个App.config文件,我试图读取,我得到这个错误,因为在我的作业实例的实例化,我有一行在我的代码是引用配置。AppSettings & Configuration.ConnectionStrings。只要确保你走的是这条路:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

并将您的配置设置放在OWSTIMER.EXE.CONFIG文件中。