English 中文(简体)
视窗服务处理致命错误
原标题:Handling fatal error in a Windows Service

我创建了一个窗口服务和安装器,监督为变更而收集的文档,并抄录任何更改“观察清单”中具体指明的目的地名录的档案。

I have a couple issues with the service: 1. It has stopped running on one occasion. (unacceptable) 2. We sometimes have to attempt to start the service several times before it "takes".

我认为,第1号问题很可能是由于在申请中没有处理致命错误。 我发现,我试图在主(金)方法中加入一条法典,但写成一个青少年读物(申请并非一个公认的类别),因此,现在也作了评论。 任何在服务中执行这一规定的适当类别的想法?

第2期很可能是排出一米的猜测。 监督员目前由网络不同机器的9个不同档案组成。 与这些来源的连接并不直接(并非都是在单一领域)。 是否有办法为服务开办设定不同的时间分配价值?

Here s the relevant code. Additional classes on request.
Thanks in advance.

Edit:错误地将主(主)(主)从我用来 de的测试中登出。 我先从WinSvc项目增加方案类别。

    //Console Test harness
        class Program
            {
                [STAThread]
                static void Main(string[] args)
                {
                    //AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                    //Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                    //Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                    //Application.EnableVisualStyles();
                    //Application.SetCompatibleTextRenderingDefault(false);
                    //Application.Run(new Form1());

                    TimedWatchList twl = new TimedWatchList(new PSU_Config(Helpers.GetConfigFile()));

                    Console.WriteLine("Press  q  to quit the sample.");
                    while (Console.Read() !=  q ) ;
                }

                static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
                {
                    HandleException((Exception)e.ExceptionObject);
                }

                static void HandleException(Exception e)
                {
                    //Handle/Log Exception Here
                }
                static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
                {
                    Logger.Loggit(e.Exception.Message);
                }
            }

    //Actual Service
       static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            static void Main()
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new Psu() 
                };
                ServiceBase.Run(ServicesToRun);
            }
        }

      public partial class Psu : ServiceBase
        {
            public Psu()
            {
                InitializeComponent();
                TimedWatchList twl = new TimedWatchList(new PSU_Config(Helpers.GetConfigFile()));
            }

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

            protected override void OnStop()
            {
            }
        }


        public class TimedWatchList
        {
            public static PSU_Config Config { get; set; }
            List<WatchFile> WatchList = new List<WatchFile>();

            public TimedWatchList(PSU_Config config)
            {
                Config = config;
                if (Config.PrintDebugMsgs) Logger.Loggit("Attempting to create TimedWatchList object");
                WatchList = WatchListFactory.GetWatchList(Helpers.GetWatchListFile());
                if (Config.PrintDebugMsgs) Logger.Loggit("TimedWatchList created");

                Timer _timer = new Timer();
                _timer.Interval += Config.Interval;
                _timer.Enabled = true;
                // register OnTimedEvent() to fire on each "tick" 
                _timer.Elapsed += OnTimedEvent;
            }

            private void OnTimedEvent(object source, ElapsedEventArgs e) 
            {
                foreach (WatchFile file in WatchList)
                {
                    file.PostOnUpdate();
                }
            }

        }//TimedWatchList class

 internal class WatchFile
    // represents a file that is being watched
    {
    #region Props
        public FileInfo SourceFile { get; set; }
        public DirectoryInfo TargetPath { get; set; }
    #endregion //Props

    #region CTOR
        public WatchFile() { }
        public WatchFile(string fileName, string sourcePath, string destPath)
        {
            SourceFile = new FileInfo(Path.Combine(sourcePath, fileName));
            TargetPath = new DirectoryInfo(destPath);
        }
        public WatchFile(FileInfo sourceFile, DirectoryInfo targetDirectory)
        {
            SourceFile = sourceFile;
            TargetPath = targetDirectory;
        }
    #endregion //CTOR

        public void PostOnUpdate()
        {
            //if (TimedWatchList.Config.PrintDebugMsgs) Logger.Loggit("WatchFile Post Event called for: " + SourceFile.Name);
            //if (TimedWatchList.Config.PrintDebugMsgs) Logger.Loggit("Stored LastModified datetime: " + LastModified);

            string targetPath = String.Format(@"{0}{1}", TargetPath.FullName, SourceFile.Name);
            {
                try
                {
                    //ensure directory exists
                    if (!Directory.Exists(TargetPath.FullName)) Directory.CreateDirectory(TargetPath.FullName);

                    //ensure file version is current
                    if (!File.Exists(targetPath) || (File.GetLastWriteTime(targetPath) != File.GetLastWriteTime(SourceFile.FullName)))
                    {
                        Logger.Loggit(String.Empty);
                        Logger.Loggit("Attempting to copy: " + SourceFile + " (" + File.GetLastWriteTime(SourceFile.FullName) + ")");
                        SourceFile.CopyTo(targetPath, true);
                        Logger.Loggit("	Copy posted.	LastModified: " + File.GetLastWriteTime(targetPath));
                    }

                }
                catch (IOException ioex)
                {
                    Logger.Loggit("Error: " + ioex.Message);
                }
                catch (Exception ex)
                {
                    Logger.Loggit("Error: " + ex.Message);
                }
            }
        }
    }// WatchFile class
最佳回答

确实没有必要进行猜测;作为一种服务,你应当把错误记录到系统事件记录上。 设立一个最高级别的手稿(如您所做的那样),但并不期望能够处理。

If the error was unhandled you re not going to be able to do anything about it there. Log it and exit. Catch the errors you can handle as soon as possible, test and design your code to not break otherwise.

你可以安排你在坠毁后自动恢复工作,但这应该是最后的手段。 Bus弄你的夸张,直截了当发生错误和原因。 我在这里看到许多“可能[有的]”和“可能还有其他的]”声明。 同样,没有任何理由进行猜测;你掌握着能够帮助你准确了解正在发生的情况的工具。

问题回答

您不妨简单地在<条码>栏/渔获栏中总结您的职能,看看你可能发现的情况。

try
{
  MainAppFunctionality();
}
catch (Exception e)
{
   //Not sure what you are going to do here, it s probably too late
}

我建议,作为开端,在您申请的各点上登录视窗户,以便你开始缩小错误的位置。

我也不清楚你为什么从视窗服务的角度使用<代码>Console.Read()。 就Vista而言,该处没有办法与桌面互动。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签