Windowservice error

淺唱寂寞╮ 提交于 2019-12-03 09:14:52

We create many services during our work and one method for debugging I've found very useful is the following:

Make your service a "dual application" that can run as a service or as a normal Windows Forms application, controlled by some command line parameter. I pass "/gui" to my services.

In void Main(string[] args) I check for the parameter:

If it is missing, I execute the code to instantiate the service (the code generated by Visual Studio).

If it is there, I run code to create a normal Windows Forms application, where the main form instantiates the service and calls OnStart and OnStop accordingly (you'll have to create wrapper methods due to visibility of OnStart and OnStop).

Of course you have to add the references to the Windows Forms assemblies manually and add code like Application.Run(...) yourself, but debugging capabilities are greatly improved without going through the hassle of the "Stop Service, Copy File, Start Service, Fail"-routine.

Most likely, there's a bug in your OnStart code which makes the instance drop out of that routine and the service manager keeps waiting.

EDIT
Here's a code sample for you of the way I create the service/gui depending on the parameter:

static void Main(string[] args)
{
    if (args.Length > 0 && args[0].Equals("/gui"))
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new FrmGui());
    }
    else
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] { new SampleService() };
        ServiceBase.Run(ServicesToRun);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!