现在的位置: 首页 > 综合 > 正文

使用C#建立WINDOWS服务

2012年08月11日 ⁄ 综合 ⁄ 共 6451字 ⁄ 字号 评论关闭
1、创建WINDOWS服务代码

  1using System;
  2using System.IO ;
  3using System.Collections;
  4using System.ComponentModel;
  5using System.Data;
  6using System.Diagnostics;
  7using System.ServiceProcess;
  8
  9namespace MyService
 10{
 11    public class MyServiceTest : System.ServiceProcess.ServiceBase
 12    {
 13        private System.Diagnostics.EventLog eventLog1;
 14        private System.Diagnostics.PerformanceCounter performanceCounter2;
 15        /// <summary> 
 16        /// 必需的设计器变量。
 17        /// </summary>

 18        private System.ComponentModel.Container components = null;
 19
 20        public MyServiceTest()
 21        {
 22            // 该调用是 Windows.Forms 组件设计器所必需的。
 23            InitializeComponent();
 24
 25            // TODO: 在 InitComponent 调用后添加任何初始化
 26        }

 27
 28        // 进程的主入口点
 29        static void Main()
 30        {
 31            System.ServiceProcess.ServiceBase[] ServicesToRun;
 32    
 33            // 同一进程中可以运行多个用户服务。若要将
 34            //另一个服务添加到此进程,请更改下行
 35            // 以创建另一个服务对象。例如,
 36            //
 37            //   ServicesToRun = New System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
 38            //
 39            ServicesToRun = new System.ServiceProcess.ServiceBase[] new MyServiceTest() };
 40
 41            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
 42        }

 43
 44        /// <summary> 
 45        /// 设计器支持所需的方法 - 不要使用代码编辑器 
 46        /// 修改此方法的内容。
 47        /// </summary>

 48        private void InitializeComponent()
 49        {
 50            this.eventLog1 = new System.Diagnostics.EventLog();
 51            this.performanceCounter2 = new System.Diagnostics.PerformanceCounter();
 52            ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
 53            ((System.ComponentModel.ISupportInitialize)(this.performanceCounter2)).BeginInit();
 54            // 
 55            // eventLog1
 56            // 
 57            this.eventLog1.Log = "MyServiceLog2";
 58            this.eventLog1.Source = "MyService2";
 59            // 
 60            // performanceCounter2
 61            // 
 62            this.performanceCounter2.CategoryName = "MyTestCount";
 63            this.performanceCounter2.CounterName = "RunCount";
 64            this.performanceCounter2.MachineName = "zxd";
 65            // 
 66            // MyServiceTest
 67            // 
 68            this.AutoLog = false;
 69            this.CanPauseAndContinue = true;
 70            this.ServiceName = "MyServiceTest";
 71            ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
 72            ((System.ComponentModel.ISupportInitialize)(this.performanceCounter2)).EndInit();
 73
 74        }

 75
 76        /// <summary>
 77        /// 清理所有正在使用的资源。
 78        /// </summary>

 79        protected override void Dispose( bool disposing )
 80        {
 81            if( disposing )
 82            {
 83                if (components != null
 84                {
 85                    components.Dispose();
 86                }

 87            }

 88            base.Dispose( disposing );
 89        }

 90
 91        /// <summary>
 92        /// 设置具体的操作,以便服务可以执行它的工作。
 93        /// </summary>

 94        protected override void OnStart(string[] args)
 95        {
 96            // TODO: 在此处添加代码以启动服务。
 97
 98            createlog();
 99            performanceCounter2.IncrementBy(2);
100
101            eventLog1.WriteEntry("My service started ("+performanceCounter2.RawValue.ToString()+")",EventLogEntryType.Information );
102
103            string fname=@"c:\myservice_test.txt";
104
105            FileStream fs=new FileStream(fname,
106                (File.Exists(fname))?FileMode.Append:FileMode.Create,
107                FileAccess.Write);
108
109            StreamWriter sw=new StreamWriter(fs);
110            //sw.a
111            sw.WriteLine("My service start:"+DateTime.Now.ToString());
112            sw.Close();
113            fs.Close();
114        }

115 
116        /// <summary>
117        /// 停止此服务。
118        /// </summary>

119        protected override void OnStop()
120        {
121            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
122            createlog();
123            eventLog1.WriteEntry("My service stoped",EventLogEntryType.Information );
124
125            string fname=@"c:\myservice_test.txt";
126
127            FileStream fs=new FileStream(fname,
128                (File.Exists(fname))?FileMode.Append:FileMode.Create,
129                FileAccess.Write);
130
131            StreamWriter sw=new StreamWriter(fs);
132            sw.WriteLine("My service stop:"+DateTime.Now.ToString());
133            sw.Close();
134            fs.Close();
135        }

136        private void createlog(){
137//            if (EventLog.SourceExists("MyServicelog2")){
138//                EventLog.CreateEventSource("MyService2","MyServicelog2");
139//            }
140//            eventLog1.Source ="MyServiceTest";
141            //这里获得的经验,当我添加应用程序日志测试成功后。我尝试添加自定义日志
142            //结果总是提示已存在MyService源,原来只要日志中写入过这个源名称
143            //就不能在自定义日志分类中使用此源
144            //另外上述注释掉的代码是手动编码添加自定义源,现在则在设计器中完成
145        }

146    
147        protected override void OnCustomCommand(int command)
148        {
149            // TODO:  添加 MyServiceTest.OnCustomCommand 实现
150            //base.OnCustomCommand (command);
151            createlog();
152            eventLog1.WriteEntry("My service command "+command.ToString(),EventLogEntryType.Information );
153
154            if (command==128){
155
156                string s=performanceCounter2.RawValue.ToString() ;
157                string fname=@"c:\myservice_test.txt";
158
159                FileStream fs=new FileStream(fname,
160                    (File.Exists(fname))?FileMode.Append:FileMode.Create,
161                    FileAccess.Write);
162
163                StreamWriter sw=new StreamWriter(fs);
164                sw.WriteLine("My service command:"+command.ToString()+" Return value: "+s+DateTime.Now.ToString());
165                sw.Close();
166                fs.Close();
167                
168            }

169        }

170
171        private void eventLog1_EntryWritten(object sender, System.Diagnostics.EntryWrittenEventArgs e)
172        {
173            //
174        }

175    }

176}

177

2、客户端

  1using System;
  2using System.Drawing;
  3using System.Collections;
  4using System.ComponentModel;
  5using System.Windows.Forms;
  6using System.Data;
  7using System.Configuration.Install ;
  8using System.Diagnostics;
  9
 10
 11namespace XmlTest
 12{
 13    

抱歉!评论已关闭.