Windows服务错误:进程意外终止

时间:2018-08-31 07:51:13

标签: c# windows-services

这是我的App.Config-

 <configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>

  <setting name="RunAsWindowsService" serializeAs="String">
    <value>True</value>
  </setting>

    <AppSettings>
      <settings>
        <settings>
    <add key="ConnectionString" value="Server=WIN-OTVR1M4I567;Database=CresijCam;Integrated Security=SSPI;" />
  </settings>
      </settings>

    </AppSettings>


</configuration>

这是我用于调用方法的代码-

public partial class Service1 : ServiceBase
    {
        Thread th = null;
        public Service1()
        {
            InitializeComponent();
             th = new Thread(AsynchronousSocketListener.StartListening);
        }


        protected override void OnStart(string[] args)
        {
            try {

                th.Start();
                // Log an event to indicate successful start.
                EventLog.WriteEntry("Successful start.", EventLogEntryType.Information);

            }
            catch(Exception ex)
            {
                // Log the exception.
                EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
            }
        }

        protected override void OnStop()
        {
            th.Abort();
        }
    }

这里是代码-

 public class AsynchronousSocketListener
{

   static string path = @"E:\F\trythis\TCPService\bin\Debug\TCPService.exe";
    static Configuration config = ConfigurationManager.OpenExeConfiguration(path);

    static string constr = config.AppSettings.Settings["ConnectionString"].Value;

    // Thread signal.  
     public static ManualResetEvent allDone = new ManualResetEvent(false);

    private AsynchronousSocketListener()
    {

    } 
    public static void StartListening()
    {
        // Establish the local endpoint for the socket.  
        // The DNS name of the computer  


        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 1200);

        // Create a TCP/IP socket.  
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and listen for incoming connections.  
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(200);

            while (true)
            {
                // Set the event to nonsignaled state.  
                 allDone.Reset();

                // Start an asynchronous socket to listen for connections.  

                listener.BeginAccept(
                    new AsyncCallback(AcceptCallback),
                    listener);

                // Wait until a connection is made before continuing.  
                 allDone.WaitOne();
            }

        }
        catch (Exception e)
        {

        }



    }


 public static  void AcceptCallback(IAsyncResult ar)
    {
        // Signal the main thread to continue.  
         allDone.Set();

        // Get the socket that handles the client request.  
        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);
        string ip = ((IPEndPoint)handler.RemoteEndPoint).Address.ToString();

        // Create the state object.  
        StateObject state = new StateObject();
        state.workSocket = handler;

        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
            new AsyncCallback(ReadCallback), state);
    }

此服务是为了创建一个TCP侦听器,该侦听器在后台连续运行并更新数据库中的数据,以便我可以通过自己的Web应用程序使用该数据。 如果您需要用于此处调用的方法的代码。我将在此处添加。但是我认为该代码不包含任何错误,因为该相同的代码正在Windows窗体应用程序中工作。

任何建议将不胜感激。谢谢

我按照此处所说的更改了代码-https://stackoverflow.com/a/27544887/9650643

从service.exe.config文件中获取连接字符串。

static Configuration config = ConfigurationManager.OpenExeConfiguration("E:\\F\\trythis\\TCPService\\bin\\Debug\\TCPService.exe");

    static string constr = config.AppSettings.Settings["ConnectionString"].Value;

enter link description here

现在我有一个不同的问题-

  

应用程序:TCPService.exe框架版本:v4.0.30319说明:   该过程由于未处理的异常而终止。

     

例外   信息:System.NullReferenceException在   TCPService.AsynchronousSocketListener..cctor()

     

异常信息:   System.TypeInitializationException在   TCPService.AsynchronousSocketListener.StartListening()在   System.Threading.ThreadHelper.ThreadStart_Context(System.Object)在   System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext,   System.Threading.ContextCallback,System.Object,Boolean)在   System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,   System.Threading.ContextCallback,System.Object,Boolean)在   System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,   System.Threading.ContextCallback,System.Object),位于   System.Threading.ThreadHelper.ThreadStart()

我尝试以所有可能的方式添加连接字符串。我现在不明白是什么导致了此错误

添加了:如何在以上代码中初始化databaseConfiguration字符串。如果可能的话,请让我知道如果我做的初始化错误。我尝试了2-3种不同的方式。  我尝试过的另一种方法是- 我删除了appsetting,并将其添加到App.config

<connectionStrings>
    <remove name="LocalSqlServer"/>
    <add name="CresijCamConnectionString" connectionString="Integrated Security=SSPI;Persist Security Info=False;Data Source=WIN-OTVR1M4I567;Initial Catalog=CresijCam" providerName="System.Data.SqlClient"/>
  </connectionStrings>

然后 我删除了我在上面的类AsynchronousSocketListener中创建的

  

静态字符串路径=   @“ E:\ F \ trythis \ TCPService \ bin \ Debug \ TCPService.exe”;

     

静态配置config =   ConfigurationManager.OpenExeConfiguration(path);

 static string constr =  config.AppSettings.Settings["ConnectionString"].Value;

并将其添加到类中-

static string constr = ConfigurationManager.ConnectionStrings["CresijCamConnectionString"].ConnectionString;

但是两者都不起作用

App.Config没有 configSection标记作为 Configurations标记的第一个子代,这就是服务无法读取设置的原因。现在它工作正常。

0 个答案:

没有答案