一、测试Windows服务

为了使Windows服务程序能够正常运行,我们需要像创建一般应用程序那样为它创建一个程序的入口点。像其他应用程序一样,Windows服务也是在Program.cs的Main()函数中完成这个操作。首先我们在Main()函数中创建一个Windows服务的实例,该实例应该是ServiceBase类的某个子类的对象,然后我们调用由基类ServiceBase类定义的一个Run()方法。然而调用Run()方法并不意味着就开始了Windows服务程序,必须要等到该对象的OnStart()方法被调用时服务才算真正开始运行。如果你想在一个Windows服务程序中同时启动多个服务,那么只要在Main()函数中定义多个ServiceBase类的子类的实例对象就可以了,方法就是创建一个ServiceBase类的数组对象。

 1 namespace WindowsServiceDemo
 2 {
 3     static class Program
 4     {
 5         /// <summary>
 6         /// 应用程序的主入口点。
 7         /// </summary>
 8         static void Main()
 9         {
10             ServiceBase[] ServicesToRun;
11             ServicesToRun = new ServiceBase[] 
12             { 
13                 //服务1
14                 new MyService(), 
15                 //服务2
16                 new Service1()
17             };
18             ServiceBase.Run(ServicesToRun);
19         }
20     }
21 }

由于Windows服务没有直接的用户交互,服务的状态必须通过记录日志才可知晓。要测试windows服务,可以通过重写服务里面的方法,在方法里面记录日志来实现。

1、新建Common类,类里面有一个WriteLog记录日志的方法。日志路径写在配置文件里面,可以实现项目的灵活性。

 1 namespace WindowsServiceDemo
 2 {
 3     public class Common
 4     {
 5         /// <summary>
 6         /// 记录日志
 7         /// </summary>
 8         /// <param name="strInfo"></param>
 9         public static void WriteLog(string strInfo)
10         {
11             string strPath=ConfigurationManager.AppSettings["FilePath"];
12             using (StreamWriter sw = new StreamWriter(strPath, true))
13             {
14                 sw.WriteLine(strInfo + ",当前时间:" + DateTime.Now.ToString());
15                 sw.Close();
16             }
17             
18         }
19     }
20 }
View Code

相关文章:

  • 2022-12-23
  • 2022-01-16
  • 2021-08-26
  • 2021-12-18
  • 2021-10-08
  • 2021-06-03
  • 2021-09-14
猜你喜欢
  • 2021-09-20
  • 2022-12-23
  • 2021-09-18
  • 2022-12-23
  • 2021-09-03
  • 2021-12-27
  • 2022-12-23
相关资源
相似解决方案