Keep C# application running

泄露秘密 提交于 2019-12-11 17:38:49

问题


I'm building a Windows Service that uses FileSystemWatcher, and runs in the background.

I don't want to keep on uninstalling and installing the service every time I want to debug, so would like to do most of my development in a normal program before moving it into a service. But I'm quite new to this, and when I run it, it just runs through the block and exits.

What would be a good way to keep the program running?


回答1:


http://einaregilsson.com/run-windows-service-as-a-console-program/

I've used this before to debug my service as a Console application based on whether its running in an interactive user environment.

public partial class DemoService : ServiceBase
{
    static void Main(string[] args)
    {
        DemoService service = new DemoService();

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



回答2:


while (true)
{
  // Execute your program's functionality here.
}



回答3:


I wrote a 7 part series a while ago titled: Building a Windows Service. It covers all the intricacies of building services, making them friendly to debug, and self-installing.

The basic feature set I was looking for was as follows:

  • Building a service that can also be used from the console
  • Proper event logging of service startup/shutdown and other activities
  • Allowing multiple instances by using command-line arguments
  • Self installation of service and event log
  • Proper event logging of service exceptions and errors
  • Controlling of start-up, shutdown and restart options
  • Handling custom service commands, power, and session events
  • Customizing service security and access control

The final result was a Visual Studio project template that creates a working service, complete with all of the above, in a single step. It's been a great time saver for me.

see Building a Windows Service – Part 7: Finishing touches for a link to the project template and install instructions.




回答4:


Here’s documentation from MSDN @ http://msdn.microsoft.com/en-us/library/7a50syb3(v=vs.80).aspx?ppud=4 . I have tried it before and it works under .NET Framework 3.x. I could not find my descriptive notes on it, at the moment.

Use the pragma #If DEBUG for debugging purposes like console outputs. Another is using the Debug object.

If you have any trouble with this, say so. I may be able to find my notes or make a Windows Service app myself, just to see if the steps on MSDN still work.



来源:https://stackoverflow.com/questions/10688727/keep-c-sharp-application-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!