C#Windows服务 - 启动然后自动停止

Inv*_*ige 5 .net c# windows service

我按照MSDN演示中的说明创建此Windows服务:创建Windows服务,成功安装后,我转到Services.msc启动Windows服务,在启动完成之前,我收到以下消息:

本地计算机上的EIWindowsService服务已启动,然后停止.如果某些服务未被其他服务或程序使用,则会自动停止.

我知道Windows服务启动正常,因为日志文件中有一个条目表明服务已启动.我在发布之前做了一些研究,并且Some Services Stop的答案自动说明问题可能是OnStart方法抛出错误,或者OnStart没有开始一个线程.所以我修改了我的代码,以便OnStart中唯一的东西是两个定时器和日志条目的启动因此不需要异常处理.我还添加了一个线程来"跳转"到另一个方法.

我再次尝试了Windows服务,我知道它"移动"到线程所指向的新方法,因为我在那里有一个日志条目,由于我正在做的一些转换而引发了aFormatException错误.我注释掉了转换,Windows服务仍然刚刚开始启动然后自动停止.

进一步的研究告诉我,我可能需要一个循环来保持方法中的处理,所以我从C-Windows Service获取信息服务并设置一个无限的while循环.我还发现可能正在进行垃圾收集,并按照MSDN Timer Class的示例部分中的建议为计时器建立了KeepAlive语句.还是一样的问题.

在这一点上,我觉得我已经完成了所有可以做的研究,所以在这里发表我的问题是合适的.我的所有代码都在下面,我会注意到在执行任何更改之前,我卸载了Windows服务,删除了安装项目,并从C#代码中删除了安装程序.然后,我进行了更改,并从指示如何设置安装程序的位置开始,再次使用演练中的说明.我每次都这样做,因为我发现如果我做了更改并且没有卸载Windows服务,删除安装项目,并删除安装程序,那么我的更改将不会对当前安装的Windows服务生效.

您可以给予的任何帮助将非常感激.我会再来这里15分钟,然后明天我会先检查一下.

SERVICE1.cs

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.Timers;

namespace EIWindowsService
{
    public partial class Service1 : ServiceBase
    {
        Logs.ErrorLog logFile = new Logs.ErrorLog();
        private System.Threading.Thread onStartThread;

        public Service1()
        {
            InitializeComponent();            
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                iTimer.Start();
                iTimer.Elapsed += new ElapsedEventHandler(iTimer_Elapsed);
                pTimer.Start();
                pTimer.Elapsed += new ElapsedEventHandler(pTimer_Elapsed);                
                onStartThread = new System.Threading.Thread(TimerValue);
                onStartThread.Start();
                logFile.SendToLog("EIWindows Service started on " + GetDate());
            }
            catch (ArgumentOutOfRangeException ex)
            {
                logFile.SendToLog("ArgumentOutOfRangeException", "EIWindowsService\\Service1.cs", "OnStart()", ex);
            } //end of ArgumentOutOfRangeException CATCH statement
        }

        protected override void OnStop()
        {
            iTimer.Stop();
            pTimer.Stop();
            logFile.SendToLog("EIWindowsService\\Service1.cs", "OnStop()", "EIWindows Service stopped on " + GetDate());

        }

        private void TimerValue()
        {
            try
            {
                   /*commented out because it was throwing an exception error*/
                   //double iTimerValue = Convert.ToDouble(iTimer.ToString());
                   //double pTimerValue = Convert.ToDouble(pTimer.ToString());
                while (1 > 0)
                {
                       //if (iTimerValue % 1800000 == 0)  //if the timer hits the 30min mark
                       //{
                       //    logFile.SendToLog("Current iTimer Value = " + iTimerValue.ToString());
                       //}
                       //if (pTimerValue % 1800000 == 0)  //if the timer hits the 30min mark
                       //{
                       //    logFile.SendToLog("Current pTimer Value = " + pTimerValue.ToString());
                       //}
                    GC.KeepAlive(iTimer);
                    GC.KeepAlive(pTimer);
                }
                   //TimerValue();
            }
            catch (OverflowException ex)
            {
                logFile.SendToLog("OverflowException", "EIWindowsService\\Service1.cs", "TimerValue()", ex);
            } //end of OverflowException CATCH statement
            catch (ArgumentException ex)
            {
                logFile.SendToLog("ArgumentException", "EIWindowsService\\Service1.cs", "TimerValue()", ex);
            } //end of ArgumentException CATCH statement
            catch (FormatException ex)
            {
                logFile.SendToLog("FormatException", "EIWindowsService\\Service1.cs", "TimerValue()", ex);
            } //end of FormatException CATCH statement
        }

        private string GetDate()
        {
            string current = "No Date Recorded";
            try
            {
                current = DateTime.Now.ToString("F");
            }
            catch (FormatException ex)
            {
                logFile.SendToLog("FormatException", "EIWindowsService\\Service1.cs", "GetDate()", ex);
            } //end of FormatException CATCH statement

            return current;
        } //end of method GetDate

        private void iTimer_Elapsed(object source, ElapsedEventArgs e)
        {
            try
            {
                iTimer.Stop();
                ImportI();
                iTimer.Start();
            }
            catch (ArgumentOutOfRangeException ex)
            {
                logFile.SendToLog("ArgumentOutOfRangeException", "EIWindowsService\\Service1.cs", "iTimer_Elapsed()", ex);
            } //end of ArgumentOutOfRangeException CATCH statement
        } //end of method iTimer_Elapsed

        private void pTimer_Elapsed(object source, ElapsedEventArgs e)
        {
            try
            {
                pTimer.Stop();
                ImportP();
                pTimer.Start();
            }
            catch (ArgumentOutOfRangeException ex)
            {
                logFile.SendToLog("ArgumentOutOfRangeException", "EIWindowsService\\Service1.cs", "pTimer_Elapsed()", ex);
            } //end of ArgumentOutOfRangeException CATCH statement
        } //end of method pTimer_Elapsed

        private void ImportI()
        {
            //does some action but commented out because it never gets here and is not relavant to this question.
        } //end of method ImportI

        private void ImportP()
        {
            //does some action but commented out because it never gets here and is not relavant to this question.
        } //end of method ImportP
    }
}
Run Code Online (Sandbox Code Playgroud)

SERVICE1.DESIGNER.CS (相关人员)

private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.pTimer = new System.Timers.Timer(10800000);  //3hrs
            this.iTimer = new System.Timers.Timer(3600000);  //1hr
            // 
            // pTimer
            // 
            this.pTimer.Enabled = true;
            // 
            // iTimer
            // 
            this.iTimer.Enabled = true;
            // 
            // Service1
            // 
            this.ServiceName = "EIWindowsService";

        }

        #endregion

        private System.Timers.Timer pTimer;
        private System.Timers.Timer iTimer;
Run Code Online (Sandbox Code Playgroud)

alf*_*alf 2

您无需创建单独的线程或担心垃圾收集器。该框架会为您处理所有这些事情。只需创建计时器,它们就会被调用。这是一个例子。

public partial class Service1 : ServiceBase
{
    private Timer timer;

    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        timer = new Timer(1000);
        timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        timer.Start();
    }

    void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        using (StreamWriter writer = File.AppendText(@"C:\Users\alfonso\Desktop\log.txt"))
        {
            writer.WriteLine(string.Format("{0} : {1}", DateTime.Now, "Logging from the service"));
        }
    }

    protected override void OnStop()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)