且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

运行WPF应用程序作为Windows服务

更新时间:2022-05-22 03:11:34

随着经验的服务规则不应该有什么样的UI的,这是因为服务通常具有非常高的权限运行,可糟糕的事情都可能发生,如果你不是超级小心你的输入(我觉得窗户的最新版本不会让你做这件事的所有,但我不是100 %确定)。如果你需要与服务进行沟通,你应该使用某种形式的IPC(WCF,管道,插座,等...)的。如果你想要一个简单的控制台程序,也可以是我知道设置了一招的服务

As a rule of thumb services should never have any kind of UI, this is because services usually run with very high privileges and can bad things can happen if you are not super careful with your inputs (I think the newest versions of windows won't let you do it at all but I am not 100% sure). if you need to communicate with a service you should use some form of IPC (wcf, pipes, sockets, ect...). If you want a simple console program that also can be a service I know of a trick set that up.

class MyExampleApp : ServiceBase
{

    public static void Main(string[] args)
    {
        if (args.Length == 1 && args[0].Equals("--console"))
        {
            new MyExampleApp().ConsoleRun();
        }
        else
        {
            ServiceBase.Run(new MyExampleApp());
        }
    }
    private void ConsoleRun()
    {
        Console.WriteLine(string.Format("{0}::starting...", GetType().FullName));

        OnStart(null);

        Console.WriteLine(string.Format("{0}::ready (ENTER to exit)", GetType().FullName));
        Console.ReadLine();

        OnStop();

        Console.WriteLine(string.Format("{0}::stopped", GetType().FullName));
    }
    //snip
}

如果你刚开始该计划将推出服务(在骂你,如果你从控制台运行的话),但如果添加放慢参数 - 控制台在启动时,程序会启动并等待你按下回车键关闭。

if you just start the program it will launch as a service (and yell at you if you run it from the console) but if you add the paramter --console when you start it the program will launch and wait for you to hit enter to close.