C # - Windows service creation and running

Windows service creation and running
 
Applicable scenarios
ASP. Net is usually a stateless provider, which does not support running code continuously or executing a piece of code regularly, so we need to build our own Windows service to run those scheduled tasks.
Services can be used when the project needs to process data regularly, such as SMS sending, email reminding, docking with other information systems and other scheduled tasks
 
Without saying much, briefly introduce how to create
 
1. Create a new service
From the Visual Studio File menu, select New>Project (or press Ctrl+Shift+N) to open the New Project window
Navigate to and select the Windows Services (. NET Framework) project template.  
 
2. Change the service name
Right click "Property", find the "ServiceName" property, and modify it to "MyService"
 
3. Add an installer
(1) Right click the Service. cs [Design] window and select Add Installer.
You can see that "serviceProcessInstall1" and "serviceInstaller1" are automatically added to the project.
 
(2) Set the main properties of the component serviceProcessInstaller1, Access: account type, LocalSystem local system service;
 
4. Add the business code required by the project
 one  using System; two  using System. Collections. Generic; three  using System. Linq; four  using System. ServiceProcess; five  using System. Text; six  using System. Threading. Tasks; seven  namespace WindowsService eight  { nine      static  class Program ten  { eleven          ///  <summary>
 twelve          /// The main entry point for the application. thirteen          ///  </summary>
 fourteen          static  void Main() fifteen  { sixteen  ServiceBase[] ServicesToRun; seventeen ServicesToRun = new ServiceBase[] eighteen  { nineteen                  new Service1() twenty  }; twenty-one  ServiceBase. Run(ServicesToRun); twenty-two  } twenty-three  } twenty-four }

Open "Program. cs", and you can see that after the service is started, first execute Service1.

Here, we have polled for 5 seconds, and write a log message as an example
(1) First, add the folder "Utils" and the class "Common. cs" to record logs
 one  using System; two  using System. Collections. Generic; three  using System. IO; four  using System. Linq; five  using System. Text; six  using System. Threading. Tasks; seven  namespace WindowsService. Utils eight  { nine      public  static  class Common ten  { eleven          public  static  void WriteLogs( string content) twelve  { thirteen              string path = AppDomain. CurrentDomain. BaseDirectory; fourteen              string LogName =  System. Reflection. MethodBase. GetCurrentMethod(). DeclaringType. Namespace. Split( ' . ' )[ zero ]; fifteen              string [] sArray = path. Split( new  string [] { LogName },  StringSplitOptions. RemoveEmptyEntries); sixteen              string aa = sArray[ zero ] + " \\ " + LogName + " Log\\ " ; seventeen path = aa; eighteen              if (! string .IsNullOrEmpty(path)) nineteen  { twenty                  if (! Directory. Exists(path)) twenty-one  { twenty-two  Directory. CreateDirectory(path); twenty-three  } twenty-four path = path + " \\ " + DateTime. Now. ToString( " yyyy-MM-dd " ) + " .txt " ; // twenty-five                  if (! File. Exists(path)) twenty-six  { twenty-seven FileStream fs = File. Create(path); twenty-eight  fs. Close(); twenty-nine  } thirty                  if (File.Exists(path)) thirty-one  { thirty-two StreamWriter sw = new StreamWriter(path, true ,  System. Text. Encoding. Default); thirty-three sw. WriteLine(DateTime.Now.ToString( " yyyy-MM-dd HH:mm:ss " ) + " ---- " +  content + " \r\n " ); thirty-four  sw. Close(); thirty-five  } thirty-six  } thirty-seven  } thirty-eight  } thirty-nine }

 

 
(2) Create business code class "HandleService. cs"
 one  using System; two  using System. Collections. Generic; three  using System. Linq; four  using System. Text; five  using System. Threading. Tasks; six  using WindowsService. Utils; seven  namespace WindowsService eight  { nine      public  class HandleService ten  { eleven          public  static  void ActionRun( ref  bool isRun) twelve  { thirteen              try { fourteen isRun = true ; fifteen                  // Business code
 sixteen Common. WriteLogs( " This is a log " ); seventeen               
 eighteen  } nineteen              catch (Exception ex) twenty  { twenty-one  Common. WriteLogs(ex.Message); twenty-two  } twenty-three              finally
 twenty-four  { twenty-five isRun = false ; twenty-six  } twenty-seven  } twenty-eight  } twenty-nine }

 

(3) Set the timing trigger function of Service1,
You need to add a timer to regularly execute the business logic in the "HandleService. cs" created in the previous step. The complete code is as follows
 one  using System; two  using System. Collections. Generic; three  using System. ComponentModel; four  using System. Data; five  using System. Diagnostics; six  using System. Linq; seven  using System. ServiceProcess; eight  using System. Text; nine  using System. Threading. Tasks; ten  using WindowsService. Utils; eleven  namespace WindowsService twelve  { thirteen      public  partial  class Service1 : ServiceBase fourteen  { fifteen          public Service1() sixteen  { seventeen  InitializeComponent(); eighteen  } nineteen System. Timers. Timer _timer = new System. Timers. Timer(); twenty          private  bool isRun = false ; twenty-one          protected  override  void OnStart( string [] args) twenty-two  { twenty-three              try
 twenty-four  { twenty-five                  int _interval = five * one thousand ; twenty-six _timer. Interval = _interval; twenty-seven _timer. AutoReset = true ; twenty-eight _timer. Enabled = true ; twenty-nine _timer. Elapsed += new System. Timers. ElapsedEventHandler(ActionRun); thirty Common. WriteLogs( " Service started " ); thirty-one  } thirty-two              catch (Exception ex) thirty-three  { thirty-four  Common. WriteLogs(ex.Message); thirty-five  } thirty-six  } thirty-seven          private  void ActionRun( object sender, System. Timers. ElapsedEventArgs e) thirty-eight  { thirty-nine              try
 forty  { forty-one                  if (! isRun) forty-two  { forty-three HandleService. ActionRun( ref isRun); forty-four  } forty-five  } forty-six              catch (Exception ex) forty-seven  { forty-eight Common. WriteLogs( " Error: " + ex.Message); forty-nine  } fifty  } fifty-one          protected  override  void OnStop() fifty-two  { fifty-three _timer. AutoReset = false ; fifty-four _timer. Enabled = false ; fifty-five  _timer. Stop(); fifty-six Common. WriteLogs( " Service stopped " ); fifty-seven  } fifty-eight  } fifty-nine  } sixty  

Generate project files. After all the project files are successfully generated, start the installation and startup of services

5. Installation and startup of services
After the project is successful, find the generated exe file and the exe.config file in the bin folder. The former is the running program, and the latter is the service configuration information. In the actual project, you can modify the service configuration information by changing the content in the config.
Installation and uninstallation are mainly used The InstallUtil.exe file provided by. NET is located in C: Windows\ Microsoft. NET \Framework64 v4.0.30319, copy to the same directory bin as exe.
 
Create a new bat file for installing, starting, uninstalling, stopping, and restarting the service
 
 one  Install. bat: two sc create MyWinService binPath= " %~dp0WindowsService.exe " start= auto three  net start MyWinService four  pause five  

 

 one  Start.bat two  net start MyWinService three  pause four  

 

 one  Stop. bat two  net stop MyWinService three pause

 

 one  Uninstall.bat two  net stop MyWinService three sc delete MyWinService binPath= " %~dp0JDWindowsService.exe " start= auto four pause

 

 one  Restart. bat two  net stop MyWinService three  net start MyWinService four pause

 

6. Run the installation file and start the service
Double click "Install. bat" to pop up a cmd window, as shown in the following figure, indicating successful installation:
 
Double click Start. bat, as shown in the figure below, to start the service successfully
 
 
7. Check whether the business code log is successfully written
Find the log file in the same directory of the project file, and find the log, as shown in the following figure:
 
You can see that the log file will be written to a log file every 5 seconds. So far, the entire service has run successfully.
 
Download the source code of this article:
Extraction code: a62m
 
posted @ 2019-09-22 22:12   y_w_k   Reading( eight thousand six hundred and forty Comments( zero edit   Collection   report