2013-06-20 95 views
1

我正在尝试使用C#制作Windows服务。如何将控制台应用程序转换为服务应用程序

我的问题是,我只有Visual Studio Express 2010,所以我不能生成“服务应用程序”。我的控制台应用程序正在运行,并使用Inno Setup将其作为服务安装。

但当然,服务没有启动。所以我的问题是,控制台应用程序和Windows服务之间的编码区别是什么 - 我必须做些什么才能使我的应用程序成为一项服务。

感谢

+1

不完全重复,但我认为这会指向正确的方向:http://stackoverflow.com/q/7764088/56778 –

回答

1

我会强烈建议看TopShelf到控制台应用程序转换为Windows服务。所需的代码更改非常少;从本质上讲

public class Service 
{ 
    public void Start() 
    { 
     // your code when started 
    } 

    public void Stop() 
    { 
     // your code when stopped 
    } 
} 

public class Program 
{ 
    public static void Main() 
    { 
     HostFactory.Run(x =>         
     { 
      x.Service<Service>(s =>      
      { 
       s.ConstructUsing(name=> new Service()); 
       s.WhenStarted(tc => tc.Start());    
       s.WhenStopped(tc => tc.Stop());   
      }); 
      x.RunAsLocalSystem();       

      x.SetDescription("My service description");  
      x.SetDisplayName("ServiceName");      
      x.SetServiceName("ServiceName");     
     });             
    } 
} 

然后在命令行安装

service.exe install 
0

我们使用这些方针的东西:

using System.ServiceProcess; 
using System.Diagnostics; 
using System; 

namespace MyApplicationNamespace 
{ 
    static class Program 
    { 
     static void Main(string[] args) 
     { 
      if (args != null && args.Length > 0) 
      {  
       switch (args[0]) 
       { 
        case "-debug": 
        case "-d": 
         StartConsole(); 
         break; 

        default: 
         break; 
       } 
      } 
      else 
      { 
       StartService(); 
      }  
     } 

     private static void StartConsole() 
     { 
      MyApp myApp = new MyApp(); 
      myApp.StartProcessing(); 
      Console.ReadLine(); 
     } 

     private static void StartService() 
     { 
      ServiceBase[] ServicesToRun; 
      ServicesToRun = new ServiceBase[] { new MyApp() }; 
      ServiceBase.Run(ServicesToRun); 
     }    
    } 
} 

版和MyApp将继承

System.ServiceProcess.ServiceBase 

你那么可以安装服务

installutil app.exe 

要从控制台运行,只需使用-d或-debug开关。

相关问题