如何将我的 C# winform 程序转换为服务程序? [英] how to convert my C# winform program to service program?

查看:80
本文介绍了如何将我的 C# winform 程序转换为服务程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将我的 C# winform 程序转换为服务程序?

how to convert my C# winform program to service program ?

我需要我的程序能像服务一样工作(比如监听器)

i need that my program will work like service (like listener)

推荐答案

正如 Darin 已经指出的那样,将 UI 应用程序转换为 Windows 服务在大多数情况下不是一个好主意.

As Darin already pointed out converting a UI application into a Windows service is in most cases not a good idea.

话虽如此,可能(或存在)边缘情况下这可能有用.
到目前为止,我还没有尝试过使用 WinForms 应用程序来执行此操作,但我认为这些步骤与我曾经做过的步骤几乎相同.
我编写了一个后端应用程序,它在 99.99% 的时间作为 Windows 服务运行,但也可以作为控制台应用程序启动,以便更轻松/更快地调试.

This being said, there maybe (or are) edge cases where this can be useful.
I've so far not tried to do it with a WinForms application, but I assume that the steps are almost identical to what I once did.
I wrote a backend application, that runs as a Windows service 99.99% of the time, but can also be started as a console application for easier / faster debugging.

你必须做的事情:

  • 防止应用程序生成多个实例(可选;参见这篇文章关于如何实现这一点)
  • 确保您的应用依赖用户交互
  • 在应用程序启动时,检查它是作为 Windows 服务运行还是在用户模式下运行
  • prevent the application from spawning multiple instances (optional; see this article on how to achieve this)
  • make sure your application does not rely on user interaction
  • upon startup of the application, check whether it is run as Windows service or in user mode

您可以通过查询 Environment.UserInteractive 来检测用户是否启动了应用程序 - 如果作为 Windows 服务启动,则返回 falsetrue> 在用户模式下启动时.

You can detect if the user started the application by querying Environment.UserInteractive - which returns false, if started as Windows service, and true when started in user mode.

您的主要方法应该如下所示:

your main method should then look something like this:

    static void Main()
    {
        // do common initialization, logging framework + the likes

        if (Environment.UserInteractive)
        {
            // start up in user mode
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new myForm());
        }
        else
        {
            // start up as Windows service
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new myService() 
            };
            ServiceBase.Run(ServicesToRun);
        }
    }

这篇关于如何将我的 C# winform 程序转换为服务程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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