导致这个C#windows服务无法启动的原因是什么?

时间:2014-05-07 12:12:25

标签: c# service

它在调试/控制台模式下运行良好,但卡在"开始"从“服务”面板启动时的状态。它与安装程序项目一起安装,显然是成功的。

代码确保日志文件经常更改。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Net.Mail;
using System.ServiceProcess;
using System.Text;
using System.Threading;

namespace FileWatchdogService
{
    public partial class FileWatchdogService : ServiceBase
    {
        private static bool fileChanged = false;

    private int WaitIntervalMs
    {
        get
        {
            try
            {
                return Convert.ToInt32(ConfigurationManager.AppSettings["MinutesTillOverdue"]) * 60 * 1000;
            }
            catch (Exception ex)
            {
                eventLog1.WriteEntry(ex.ToString());
                return 15 * 60 * 1000;
            }
        }
    }

    public FileWatchdogService()
    {
        InitializeComponent();

        if (!System.Diagnostics.EventLog.SourceExists("FileWatchdog"))
        {
            System.Diagnostics.EventLog.CreateEventSource(
                "FileWatchdog", "CoreService log watchdog");
        }
        eventLog1.Source = "FileWatchdog";
        eventLog1.Log = "CoreService log watchdog";
    }

    protected override void OnStart(string[] args)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(WatchFile));
    }

    protected override void OnStop()
    {

        eventLog1.WriteEntry("Service shut down at " + Convert.ToString(DateTime.Now));
    }

    static void Main(string[] args)
    {
        FileWatchdogService service = new FileWatchdogService();

        if (Environment.UserInteractive)
        {
            service.OnStart(args);
            Console.WriteLine("Press any key to stop program");
            Console.Read();
            service.OnStop();
        }
        else
        {
            ServiceBase.Run(service);
        }

    }

    private void WatchFile(object nothing)
    {
        try
        {
            eventLog1.WriteEntry("Initiating watchdog for " + ConfigurationManager.AppSettings["FilePath"] + "  at " + Convert.ToString(DateTime.Now));
            while (true)
            {
                FileSystemWatcher watcher = new FileSystemWatcher();
                watcher.Path = Path.GetDirectoryName(ConfigurationManager.AppSettings["FilePath"]);
                watcher.Filter = Path.GetFileName(ConfigurationManager.AppSettings["FilePath"]);
                watcher.Changed += new FileSystemEventHandler(ProcessChangeEvent);
                watcher.WaitForChanged(WatcherChangeTypes.Changed, WaitIntervalMs);

                if (fileChanged) // Reset the flag for next iteration of the loop
                    fileChanged = false;
                else
                    SendNotificationEmails(); // Watcher timed out
            }

        }
        catch (Exception ex)
        {
            eventLog1.WriteEntry(ex.ToString());
            throw;
        }
    }

    static void ProcessChangeEvent(object o, FileSystemEventArgs args)
    {
        fileChanged = true;
    }

    private void SendNotificationEmails()
    {
        try
        {
            eventLog1.WriteEntry("Timeout of " + ConfigurationManager.AppSettings["MinutesTillOverdue"] + " elapsed at " + Convert.ToString(DateTime.Now));
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            msg.From = new MailAddress(ConfigurationManager.AppSettings["EmailFrom"]);
            msg.Subject = ConfigurationManager.AppSettings["EmailSubject"];

            string[] recipients = ConfigurationManager.AppSettings["EmailRecipients"].Split(';');

            foreach (string recipient in recipients)
            {
                msg.To.Add(new MailAddress(recipient));
            }

            msg.Body = "File " + ConfigurationManager.AppSettings["FilePath"] + " on " +
                       ConfigurationManager.AppSettings["ServerName"];
            msg.Body += " has not changed in " + ConfigurationManager.AppSettings["MinutesTillOverdue"] + " minutes.";
            msg.Priority = MailPriority.High;

            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["SMTPServer"]);

            eventLog1.WriteEntry("Sending emails from " + msg.From + " to " + msg.To + " through server " + client.Host);
            client.Send(msg);
            msg = null;
        }
        catch (Exception ex)
        {
            eventLog1.WriteEntry("Error in SendNotificationEmails: " + ex.ToString());
        }
    }
}

}

0 个答案:

没有答案