西西軟件園多重安全檢測下載網(wǎng)站、值得信賴的軟件下載站!
軟件
軟件
文章
搜索

首頁編程開發(fā)C#.NET → 創(chuàng)建Windows服務(wù)的幾種方式總結(jié)

創(chuàng)建Windows服務(wù)的幾種方式總結(jié)

相關(guān)軟件相關(guān)文章發(fā)表評(píng)論 來源:西西整理時(shí)間:2012/5/28 16:27:23字體大。A-A+

作者:佚名點(diǎn)擊:220次評(píng)論:5次標(biāo)簽: Windows服務(wù)

Windows服務(wù)管理器1.2.5G綠色免費(fèi)版
  • 類型:系統(tǒng)優(yōu)化大小:20KB語言:中文 評(píng)分:5.0
  • 標(biāo)簽:
立即下載

最近由于工作需要,寫了一些windows服務(wù)程序,有一些經(jīng)驗(yàn),我現(xiàn)在總結(jié)寫出來。
目前我知道的創(chuàng)建創(chuàng)建Windows服務(wù)有3種方式:
a.利用.net框架類ServiceBase
b.利用組件Topshelf
c.利用小工具instsrv和srvany

下面我利用這3種方式,分別做一個(gè)windows服務(wù)程序,程序功能就是每隔5秒往程序目錄下記錄日志:

a.利用.net框架類ServiceBase

本方式特點(diǎn):簡單,兼容性好

通過繼承.net框架類ServiceBase實(shí)現(xiàn)

第1步: 新建一個(gè)Windows服務(wù)

    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服務(wù))
installutil /u   WindowsService_test.exe  (卸載Windows服務(wù))

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

b.利用組件Topshelf

本方式特點(diǎn):代碼簡單,開源組件,Windows服務(wù)可運(yùn)行多個(gè)實(shí)例

Topshelf是一個(gè)開源的跨平臺(tái)的服務(wù)框架,支持Windows和Mono,只需要幾行代碼就可以構(gòu)建一個(gè)很方便使用的服務(wù). 官方網(wǎng)站:http://topshelf-project.com

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

第2步:創(chuàng)建一個(gè)服務(wù)類MyClass,里面包含兩個(gè)方法Start和Stop,還包含一個(gè)定時(shí)器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宿主我們的服務(wù),主要是Topshelf如何設(shè)置我們的服務(wù)的配置和啟動(dòng)和停止的時(shí)候的方法調(diào)用

    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 ( );

                //服務(wù)的描述
                x.SetDescription ( "Topshelf_Description" );
                //服務(wù)的顯示名稱
                x.SetDisplayName ( "Topshelf_DisplayName" );
                //服務(wù)名稱
                x.SetServiceName ( "Topshelf_ServiceName" );

            } );
        }
    }

第4步: cmd命令

ConsoleApp_Topshelf.exe  install    (安裝Windows服務(wù))

ConsoleApp_Topshelf.exe  uninstall  (卸載Windows服務(wù))

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

c.利用小工具instsrv和srvany

本方式特點(diǎn):代碼超級(jí)簡單,WindowsForm程序即可,并支持程序交互(本人最喜歡的特點(diǎn)),好像不支持win7,支持xp win2003

首先介紹2個(gè)小工具:

instsrv.exe:用以安裝和卸載可執(zhí)行的服務(wù)

srvany.exe:用于將任何EXE程序作為Windows服務(wù)運(yùn)行

這2個(gè)工具都是是Microsoft Windows Resource Kits工具集的實(shí)用的小工具 

你可以通過下載并安裝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步:安裝,卸載

服務(wù)的安裝步驟分5小步:

(1)打開CMD,輸入以下內(nèi)容,其中WindowsForms_WindowsService為你要?jiǎng)?chuàng)建的服務(wù)名稱

格式:目錄絕對(duì)路徑\instsrv  WindowsForms_WindowsService  目錄絕對(duì)路徑\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)鼠標(biāo)右鍵單擊WindowsForms_WindowsService,創(chuàng)建一個(gè)"項(xiàng)",名稱為"Parameters"

(4)鼠標(biāo)左鍵單擊"Parameters",在右邊點(diǎn)擊鼠標(biāo)右鍵,創(chuàng)建一個(gè)"字符串值"(REG_SZ),名稱為"Application",數(shù)值數(shù)據(jù)里填寫目錄下可執(zhí)行文件的絕對(duì)路徑+文件名

例如:

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

(5)打開services.msc服務(wù)控制面板,找到WindowsForms_WindowsService服務(wù),鼠標(biāo)右鍵-屬性-登陸,勾選"允許服務(wù)與桌面交互"

啟動(dòng)服務(wù),可以看到程序界面


 

卸載服務(wù)

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

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

    相關(guān)評(píng)論

    閱讀本文后您有什么感想? 已有人給出評(píng)價(jià)!

    • 8 喜歡喜歡
    • 3 頂
    • 1 難過難過
    • 5 囧
    • 3 圍觀圍觀
    • 2 無聊無聊

    熱門評(píng)論

    最新評(píng)論

    發(fā)表評(píng)論 查看所有評(píng)論(5)

    昵稱:
    表情: 高興 可 汗 我不要 害羞 好 下下下 送花 屎 親親
    字?jǐn)?shù): 0/500 (您的評(píng)論需要經(jīng)過審核才能顯示)