Dotnet tips: Cách tạo một ứng dụng Service window với C# .Net - Creating a Windows Service Using C#

Windows Services là tính năng quan trọng nhất cho các ứng dụng lâu dài để chạy các dịch vụ tự động ngay sau khi khởi động hệ thống.Chúng tôi có thể tự điều khiển các Dịch vụ này bằng cách bắt đầu và dừng tại một thời điểm cụ thể.

Bạn có thể xem những window service chạy bằng cách Run > nhập services.msc và Enter:



Các bước để tạo windows Service với C#:

Bước 1:
Mở Visual studio, tạo dự án Windows Service


Bước 2: 

Mở file  Service1.cs file . Add this code to that file

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Threading;

namespace WindowsService1
{
   public partial class Service1 : ServiceBase
   {

public Service1()
{
   InitializeComponent();
}

static void run()

{
//while (true)
{StreamWriter str = new StreamWriter("D:\\ContinuosLoop.txt"true);
str.WriteLine("Visit DotNetFunda Regularly");
str.Close();
}
}

Thread thr = new Thread(new ThreadStart(run));
protected override void OnStart(string[] args)
{
StreamWriter str = new StreamWriter("D:\\Log.txt"true);
str.WriteLine("Service started on : " + DateTime.Now.ToString());
str.Close();
thr.Start();
}

protected override void OnStop()
{

StreamWriter str = new StreamWriter("D:\\Log.txt"true);
str.WriteLine("Service stoped on : " + DateTime.Now.ToString());
str.Close();
thr.Abort();
}
}
}

Step 3:

We cannot directly run the service what we need to be done is add an installer. For that go back to Service1.cs[Design] file and right click and select AddInstaller option in this way

Now the Screen looks like this with 2 options this is ProjectInstaller.cs[Design]


 

Step 4:

Now we have 2 controls namely
      1) ServiceProcessInstaller1
            For this we have to change the Account Property to LocalSytem       
      2) ServiceInstaller1
For this we have to change the start type to manual and make sure you service name is well remembered.I gave ~~~SriService~~~ as in my example.
With this the coding part is completed now build the solution which will create the necessary files in bin folder.

Step 5:

As you all know inorder to run this service we have to install this service for that open VisualStudio Command Prompt. Go that the project path which was created by you untill the Project/bin/debug folder in this way

   Inorder to install we have to type installutil -i WindowsService1.exe at that path which looks like this

Step 6:

Now after successful installation you will recieve an message stating that "The Transacted install has completed" . If you get this that means your installation is successful now you can go and wacth the services folder to that go to control panel/perforamanceMaintainance/AdministartiveTools/Services.
At that palce you could see your service in this way

 

Step 7:

Now start the service. As per our coding after starting the service we create 2 text documents in the D: drive as per my example. Those are ContinousLoop.txt and Log.txt
In Log.txt the time and date of the service started and stopped will be displayed.
If you could observe i commented a line with while (true) in Service1.cs file. If we uncomment it, the line "Visit DotNetFunda Regularly" prints continuosly untill and unless we explicitly stop the service. so as i uncommented it that line will be displayed only once.
The final text documents will look like this

Conclusion

By this way we can create a Windows Service and can work with it accordingly. Hope I provided useful information in this article. Please provide your comment to imrpove this article if you feel so. Thanks!

Like