This blog is related to creating a Windows services application. Explain in detail how to implement window services with DotNet.
Step 1. Name your project and create the Project Window Service (.net Framework).
Step 2. You can go into the app.config file and put “appsetting” under the configuration tags.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ThreadLine" value="1" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>
Step 3. In service1.cs, go to the page, click the left menu, select view code (F7), and copy the code below.
[RunInstaller(true)]
public partial class Service1 : ServiceBase
{
int SchduleTime = Convert.ToInt16(ConfigurationSettings.AppSettings["ThreadLine"]);
public Thread worker = null;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
ThreadStart start = new ThreadStart(Working);
worker = new Thread(start);
worker.Start();
}
catch (Exception)
{
throw;
}
}
public void Working()
{
while (true)
{
string path = "C:\\sample.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine("path => " + path);
writer.WriteLine(string.Format("Window Service Log2" + DateTime.Now.ToString()));
writer.Close();
}
Thread.Sleep(TimeSpan.FromMinutes(SchduleTime));
}
}
protected override void OnStop()
{
try
{
if ((worker != null) & worker.IsAlive)
{
worker.Abort();
}
}
catch (Exception)
{
throw;
}
}
}
Step 4. In that life menu, go to the service1.cs page and click “add installer.” Then it has two boxes, the first of which is ServiceProcessInstaller1 and the second of which is ServiceInstaller1.
You can start with the menu. Navigate to the property section using the left menu. Change the name of the account to local system. After that, you can go to the serviceinstaller1 property section and put in a service name like “MyService.” After that, build the project.
Step 5. Click on the window menu and type “cmd” (administrator. After that, type the command
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
Install command
installutil.exe -i {{project bin path}}
Example. installutil.exe -i C:\Users\*******\Desktop\Job\WindowService.exe
Uninstall command
installutil.exe -u {{project bin path}}
installutil.exe -u C:\Users\*******\Desktop\Job\WindowService.exe