c#Windows服务启动然后停止

时间:2014-09-18 15:03:33

标签: c# windows service timer

下面的代码构建没有任何错误,并作为控制台应用程序运行良好。但是现在我已经将它变成了WindowsService并使用C:\ WINDOWS \ Microsoft.NET \ Framework \ v4.0.30319 \ InstallUtil来成功安装它。它一启动就会停止。我觉得我错过了一些简单的东西,一旦另一双眼睛注视着它,我就会永远地打击自己。

请原谅你看到的烂摊子。我会在它正常工作后清理它。提前感谢您提供的任何帮助。

Service1.cs

 namespace LGCDialHome
    {
        public partial class Service1 : ServiceBase
        {
            private System.Timers.Timer _timer = null;

            public Service1()
            {
                InitializeComponent();

                System.Timers.Timer stateTimer = new System.Timers.Timer(60000);
            }

            protected override void OnStart(string[] args)
            {
                try
                {
                    EventLog.WriteEntry("Dial Home service started : " + DateTime.Now);
                    _timer = new System.Timers.Timer();
                    _timer.Interval = 10000; //in milliseconds

                    EventLog.WriteEntry("Timer Interval is : " + _timer.Interval);

                    _timer.Elapsed += timer_Elapsed;
                    _timer.Start();
                }

                catch (Exception ex)
                {
                    EventLog.WriteEntry("Dial Home service error : " + ex);
                }

            }

            protected override void OnStop()
            {
                EventLog.WriteEntry("Dial Home service Stopped : " + DateTime.Now);
            }

            protected void timer_Elapsed(object sender, ElapsedEventArgs e)
            {
                int invokeCount = 0;
                int maxCount = 10;
                string host = Environment.MachineName;
                string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                string uname = Environment.UserName;

                try
                {
                    _timer.Stop();
                    Console.WriteLine("{0} Checking status {1,2}.",
                    DateTime.Now.ToString("h:mm:ss.fff"),(++invokeCount).ToString());
                    Console.WriteLine("Host -> {0} \r\nNTID -> {1}", host, user);
                    if (invokeCount == maxCount)
                    {
                        invokeCount = 0;
                    }
                }
                catch (Exception ex)
                {
                    EventLog.WriteEntry("Dial Home service error : " + ex);
                }

                finally
                {
                    _timer.Start();
                }
            }

        }
    }

1 个答案:

答案 0 :(得分:1)

嗯,您需要调试代码,但附加到Windows服务与调试其他类型的项目有点不同。

尝试以下方法:

1-在OnStart()方法的最开始,添加以下行:

System.Threading.Thread.Sleep(10000);

2-在上一行之后立即在下一行上设置断点。使用InstallUtil构建并重新安装您的服务。

3-开始服务。

4-在Visual Studio中,单击Debug -> Attach to Process

5-在Available Processes列表中查找您的服务并附加到该服务。这将导致断点被触发,并允许您调试代码以查看是否抛出任何异常(通过查看您的代码,我觉得问题可能与安全性有关。服务运行的用户可能不会可以访问EventLog或其他内容。

注意:启动服务后,您有10秒钟执行第4步和第5步。如果您认为需要更多时间,请将睡眠值更改为20000(20秒)。

相关问题