Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#Windows服务-自动启动然后停止_C#_.net_Windows_Service - Fatal编程技术网

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

C#Windows服务-自动启动然后停止,c#,.net,windows,service,C#,.net,Windows,Service,我正在按照说明创建此windows服务,安装成功后,我转到Services.msc启动windows服务,在它完成启动之前,我收到以下消息: 本地计算机上的EIWindowsService服务已启动,然后停止。如果某些服务未被其他服务或程序使用,则会自动停止 我知道Windows服务启动正常,因为日志文件中有一个条目说明服务已启动。在这里发布之前,我做了一些研究,结果表明问题可能是OnStart方法抛出了错误,或者OnStart没有启动线程。所以我修改了我的代码,使得OnStart中唯一的事情就

我正在按照说明创建此windows服务,安装成功后,我转到Services.msc启动windows服务,在它完成启动之前,我收到以下消息:

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

我知道Windows服务启动正常,因为日志文件中有一个条目说明服务已启动。在这里发布之前,我做了一些研究,结果表明问题可能是OnStart方法抛出了错误,或者OnStart没有启动线程。所以我修改了我的代码,使得OnStart中唯一的事情就是启动两个计时器和日志条目,因此不需要异常处理。我还添加了一个线程来“跳转”到另一个方法

我再次尝试了windows服务,我知道它“移动”到了线程指向的新方法,因为我在其中有一个日志条目,由于我正在进行转换而引发了FormatException错误。我注释掉了转换,windows服务仍然只是开始启动,然后自动停止

进一步的研究向我表明,我可能需要一个循环来保持方法中的处理,因此我从中获取信息并设置一个无限while循环。我还发现可能正在进行垃圾收集,并为计时器建立了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
    }
}
服务1.DESIGNER.CS(相关人员)


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

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()
    {
    }
}

其他一些东西可能会帮助一些人看到这篇文章,但上面的解决方案不起作用。当我遇到此问题时,我已将其添加到Windows服务的配置中:

<system.web>
    <compilation debug ="true" />    
</system.web>


我添加了这一点,以便在本地运行该服务时可以将调试器附加到该服务,但是,当我尝试将该服务移动到另一台服务器时,它给出了指定的错误。通过从配置中删除此项,服务再次工作。

Alfonso,非常感谢您的回复,但我的问题不是计时器不工作,而是发生了一些“不”的事情,导致Windows认为此服务未在使用,因此它会自动停止它。现在我确实注意到,您没有像我一样在Service1.Designer.cs中的InitializeComponent方法中定义计时器,而是将其作为Service1类中的全局变量。这可能是我的问题吗?我是否需要将计时器更改为全局变量?我会测试一下,然后告诉你。不,我认为这不是问题所在。可能您的OnStart方法中有什么东西正在引发异常,并且由于您仅处理ArgumentOutOfRange异常,服务正在终止。Alfonso,请接受您对我的OnStart仅处理ArgumentOutOfRange异常的评论,我对所有语句进行了常规异常处理,发现错误是从日志文件中抛出的。看来这个问题已经解决了。谢谢你的帮助。
<system.web>
    <compilation debug ="true" />    
</system.web>