c# - 如何使用 Visual c# Express 制作服务应用程序?

标签 c# service

我已经构建了一个应用程序来解析 Xml 文件以将数据集成到 mssql 数据库中。我正在使用 Visual C# Express。有一种方法可以使用 Express Edition 提供服务,还是我必须让 Visual Studio 来做?

最佳答案

当然可以。您甚至可以使用 csc 来完成。 VS 中唯一的东西就是模板。但您可以自己引用 System.ServiceProcess.dll。

要点:

  • 编写一个继承自ServiceBase的类
  • 在您的 Main() 中,使用 ServiceBase.Run(yourService)
  • ServiceBase.OnStart 覆盖中,生成您需要完成工作的任何新线程等(Main() 需要立即退出,否则将被视为启动失败)

示例代码

非常基本的模板代码是:

程序.cs:

using System;
using System.ServiceProcess;

namespace Cron
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            System.ServiceProcess.ServiceBase.Run(new CronService());
        }
    }
}

CronService.cs:

using System;
using System.ServiceProcess;

namespace Cron
{
    public class CronService : ServiceBase
    {
        public CronService()
        {
            this.ServiceName = "Cron";
            this.CanStop = true;
            this.CanPauseAndContinue = false;
            this.AutoLog = true;
        }

        protected override void OnStart(string[] args)
        {
           // TODO: add startup stuff
        }

        protected override void OnStop()
        {
           // TODO: add shutdown stuff
        }
    }
}

CronInstaller.cs:

using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

[RunInstaller(true)]
public class CronInstaller : Installer
{
  private ServiceProcessInstaller processInstaller;
  private ServiceInstaller serviceInstaller;

  public CronInstaller()
  {
    processInstaller = new ServiceProcessInstaller();
    serviceInstaller = new ServiceInstaller();

    processInstaller.Account = ServiceAccount.LocalSystem;
    serviceInstaller.StartType = ServiceStartMode.Manual;
    serviceInstaller.ServiceName = "Cron"; //must match CronService.ServiceName

    Installers.Add(serviceInstaller);
    Installers.Add(processInstaller);
  } 
}  

.NET 服务应用程序的安装方式与普通服务应用程序不同(即您不能使用 cron.exe/install 或其他一些命令行参数。相反,您必须使用.NET SDK 的 InstallUtil:

InstallUtil /LogToConsole=true cron.exe

资源

关于c# - 如何使用 Visual c# Express 制作服务应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/569606/

相关文章:

c# - 将列中的 XML 转换为表

c# - 如何从 C# 中的方法返回 VB6 Variant 类型的等效项

c# - 取消锁定 session 事件

c - Windows 键盘 Hook 无法作为服务运行

java - Android 服务无法启动 - 在 list 中...但什么也没有?

c# - 将二维数组转换为位图图像。 C#

c# - LINQ-to-SQL 查询何时执行?

android在应用程序运行时不时在后台运行服务

networking - kubernetes:主机外部无法访问服务

c# - 管理服务 : log user into desktop, 产生一个可以与桌面交互的进程