将 WPF 应用程序作为 Windows 服务运行 [英] Run a WPF Application as a Windows Service

查看:38
本文介绍了将 WPF 应用程序作为 Windows 服务运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在开发一个 Windows Presentation Foundation 应用程序,我们希望它能够作为 Windows 服务运行.

We are developing a Windows Presentation Foundation Application that we would like to be able run as a Windows Service.

有人做过类似的事情吗?
可能吗?

Anyone done something like that?
Is it possible?

我们不需要与桌面或任何 GUI 进行交互,如果有一个可以通过命令行(有效)或作为服务使用 GUI 运行的应用程序就好了.

We don't need to interact with the Desktop or any GUI, it would just be nice to have one App that we can run with a GUI, from the Command Line (that works) or as a Service.

期待有趣的输入:-)

推荐答案

根据经验,服务不应该有任何类型的 UI.这是因为服务通常以非常高的权限运行,如果您对输入不十分小心,可能会发生不好的事情.(我认为最新版本的 Windows 根本不允许您从服务创建 UI,但我不能 100% 确定.)

As a rule of thumb services should never have any kind of UI. This is because services usually run with very high privileges and bad things can happen if you are not super careful with your inputs. (I think the newest versions of Windows won't let you create UI from a service at all but I am not 100% sure.)

如果您需要与服务通信,则应使用某种形式的 IPC(WCF、管道、套接字...).如果你想要一个简单的控制台程序也可以是一个服务,我知道一个设置它的技巧:

If you need to communicate with a service, you should use some form of IPC (WCF, pipes, sockets, ...). If you want a simple console program that can also be a service, I know of a trick to 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
}

如果你刚启动程序,它会作为一个服务启动(如果你从控制台运行它会冲你大喊大叫),但是如果你在启动它时添加参数 --console,程序将启动并等待您按 Enter 键关闭.

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.

这篇关于将 WPF 应用程序作为 Windows 服务运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆