(轉)建立Windows服務(Windows Services)N種方式總結

來源:互聯網
上載者:User

標籤:dll   代碼   右鍵   tar   shel   cep   允許   啟動服務   mac   

轉自:http://www.cnblogs.com/aierong/archive/2012/05/28/2521409.html

最近由於工作需要,寫了一些windows服務程式,有一些經驗,我現在總結寫出來。
目前我知道的建立建立Windows服務有3種方式:
a.利用.net架構類ServiceBase
b.利用組件Topshelf
c.利用小工具instsrv和srvany

下面我利用這3種方式,分別做一個windows服務程式,程式功能就是每隔5秒往程式目錄下記錄日誌:

 

a.利用.net架構類ServiceBase

本方式特點:簡單,相容性好

通過繼承.net架構類ServiceBase實現

第1步: 建立一個Windows服務

    public partial class Service1 : ServiceBase    {        readonly Timer _timer;        private static readonly string FileName = Path.GetDirectoryName ( Assembly.GetExecutingAssembly ( ).Location ) + @"\" + "test.txt";        public Service1 ( )        {            InitializeComponent ( );            _timer = new Timer ( 5000 )            {                AutoReset = true ,                Enabled = true            };            _timer.Elapsed += delegate ( object sender , ElapsedEventArgs e )            {                this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );            };        }        protected override void OnStart ( string [ ] args )        {            this.witre ( string.Format ( "Start DateTime {0}" , DateTime.Now ) );        }        protected override void OnStop ( )        {            this.witre ( string.Format ( "Stop DateTime {0}" , DateTime.Now ) + Environment.NewLine );        }        void witre ( string context )        {            StreamWriter sw = File.AppendText ( FileName );            sw.WriteLine ( context );            sw.Flush ( );            sw.Close ( );        }    }

第2步: 添加Installer

    [RunInstaller ( true )]    public partial class Installer1 : System.Configuration.Install.Installer    {        private ServiceInstaller serviceInstaller;        private ServiceProcessInstaller processInstaller;        public Installer1 ( )        {            InitializeComponent ( );            processInstaller = new ServiceProcessInstaller ( );            serviceInstaller = new ServiceInstaller ( );            processInstaller.Account = ServiceAccount.LocalSystem;            serviceInstaller.StartType = ServiceStartMode.Automatic;            serviceInstaller.ServiceName = "my_WindowsService";            serviceInstaller.Description = "WindowsService_Description";            serviceInstaller.DisplayName = "WindowsService_DisplayName";            Installers.Add ( serviceInstaller );            Installers.Add ( processInstaller );        }      }

第3步:安裝,卸載 
Cmd命令
installutil      WindowsService_test.exe  (安裝Windows服務)
installutil /u   WindowsService_test.exe  (卸載Windows服務)

代碼下載:http://files.cnblogs.com/aierong/WindowsService_test.rar

 

b.利用組件Topshelf

本方式特點:代碼簡單,開源組件,Windows服務可運行多個執行個體

Topshelf是一個開源的跨平台的服務架構,支援Windows和Mono,只需要幾行代碼就可以構建一個很方便使用的服務. 官方網站:http://topshelf-project.com

 

第1步:引用程式集TopShelf.dll和log4net.dll

第2步:建立一個服務類MyClass,裡麵包含兩個方法Start和Stop,還包含一個定時器Timer,每隔5秒往文字檔中寫入字元

    public class MyClass    {        readonly Timer _timer;        private static readonly string FileName = Directory.GetCurrentDirectory ( ) + @"\" + "test.txt";        public MyClass ( )        {            _timer = new Timer ( 5000 )            {                AutoReset = true ,                Enabled = true            };            _timer.Elapsed += delegate ( object sender , ElapsedEventArgs e )            {                this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );            };        }        void witre ( string context )        {            StreamWriter sw = File.AppendText ( FileName );            sw.WriteLine ( context );            sw.Flush ( );            sw.Close ( );        }        public void Start ( )        {            this.witre ( string.Format ( "Start DateTime {0}" , DateTime.Now ) );        }        public void Stop ( )        {            this.witre ( string.Format ( "Stop DateTime {0}" , DateTime.Now ) + Environment.NewLine );        }    }

第3步:使用Topshelf宿主我們的服務,主要是Topshelf如何設定我們的服務的配置和啟動和停止的時候的方法調用

    class Program    {        static void Main ( string [ ] args )        {            HostFactory.Run ( x =>            {                x.Service<MyClass> ( ( s ) =>                {                    s.SetServiceName ( "ser" );                    s.ConstructUsing ( name => new MyClass ( ) );                    s.WhenStarted ( ( t ) => t.Start ( ) );                    s.WhenStopped ( ( t ) => t.Stop ( ) );                } );                x.RunAsLocalSystem ( );                //服務的描述                x.SetDescription ( "Topshelf_Description" );                //服務的顯示名稱                x.SetDisplayName ( "Topshelf_DisplayName" );                //服務名稱                x.SetServiceName ( "Topshelf_ServiceName" );            } );        }    }

第4步: cmd命令

ConsoleApp_Topshelf.exe  install    (安裝Windows服務)

ConsoleApp_Topshelf.exe  uninstall  (卸載Windows服務)

 

代碼下載:http://files.cnblogs.com/aierong/ConsoleApp_Topshelf.rar

 

c.利用小工具instsrv和srvany

本方式特點:代碼超級簡單,WindowsForm程式即可,並支援程式互動(本人最喜歡的特點),好像不支援win7,支援xp win2003

首先介紹2個小工具:

instsrv.exe:用以安裝和卸載可執行檔服務

srvany.exe:用於將任何EXE程式作為Windows服務運行

 

這2個工具都是是Microsoft Windows Resource Kits工具集的實用的小工具 

你可以通過下載並安裝Microsoft Windows Resource Kits獲得 http://www.microsoft.com/en-us/download/details.aspx?id=17657

 

第1步: 建立WindowsForm程式

   public partial class Form1 : Form    {        Timer _timer;        private static readonly string FileName = Application.StartupPath + @"\" + "test.txt";        public Form1 ( )        {            InitializeComponent ( );        }        private void Form1_Load ( object sender , EventArgs e )        {            _timer = new Timer ( )            {                Enabled = true ,                Interval = 5000            };            _timer.Tick += delegate ( object _sender , EventArgs _e )            {                this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );            };        }        void _timer_Tick ( object sender , EventArgs e )        {            throw new NotImplementedException ( );        }        void witre ( string context )        {            StreamWriter sw = File.AppendText ( FileName );            sw.WriteLine ( context );            sw.Flush ( );            sw.Close ( );        }        private void button1_Click ( object sender , EventArgs e )        {            MessageBox.Show ( "Hello" );        }    }

 

 

第2步:安裝,卸載

服務的安裝步驟分5小步:

(1)開啟CMD,輸入以下內容,其中WindowsForms_WindowsService為你要建立的服務名稱

格式:目錄絕對路徑\instsrv  WindowsForms_WindowsService  目錄絕對路徑\srvany.exe

例如:

D:\TempWork\win\Debug\instsrv.exe  WindowsForms_WindowsService  D:\TempWork\win\Debug\srvany.exe

 

(2)regedit開啟登錄編輯程式,找到以下目錄

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WindowsForms_WindowsService

 

(3)滑鼠右鍵單擊WindowsForms_WindowsService,建立一個"項",名稱為"Parameters"

 

(4)滑鼠左鍵單擊"Parameters",在右邊點擊滑鼠右鍵,建立一個"字串值"(REG_SZ),名稱為"Application",數值資料裡填寫目錄下可執行檔的絕對路徑+檔案名稱

例如:

D:\TempWork\win\Debug\WindowsFormsApplication_Exe.exe

 

(5)開啟services.msc服務控制台,找到WindowsForms_WindowsService服務,滑鼠右鍵-屬性-登陸,勾選"允許服務與案頭互動"

 

啟動服務,可以看到程式介面

 


 

卸載服務

D:\TempWork\win\Debug\instsrv.exe WindowsForms_WindowsService REMOVE

 

代碼下載:http://files.cnblogs.com/aierong/WindowsFormsApplication_Exe.rar

 

(轉)建立Windows服務(Windows Services)N種方式總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.