WindowService-Vijay
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TestWindowsService
{
public partial class Service1 : ServiceBase
{
int scheduleTime = Convert.ToInt32(ConfigurationSettings.AppSettings["ThreadTime"]);
Thread worker = null;
ProcessLog processLog = null;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
processLog = new ProcessLog();
string strMessgae = "Service Start";
try
{
processLog.ProcessLogFile(strMessgae);
ThreadStart start = new ThreadStart(Working);
worker = new Thread(start);
worker.Start();
}
catch (Exception ex)
{
ErrorLog errorLog = new ErrorLog();
errorLog.ErrorlogFile(ex.Message);
}
}
public void Working()
{
try
{
while (true)
{
string path = "D:\\Logs\\ServiceTesting.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
//Divide By Zero Exception
int c = 0;
c = 100 / c;
writer.WriteLine(string.Format("Window Service is called on" + DateTime.Now.ToString("dd/mm/yyyy hh:mm:ss tt") + ""));
writer.Close();
}
Thread.Sleep(scheduleTime * 60 * 1000);
}
}
catch (Exception ex)
{
ErrorLog errorLog = new ErrorLog();
errorLog.ErrorlogFile(ex.Message);
}
}
protected override void OnStop()
{
processLog = new ProcessLog();
string strMessage = "Service Stop";
try
{
processLog.ProcessLogFile(strMessage);
if (worker != null & worker.IsAlive)
{
worker.Abort();
}
}
catch (Exception ex)
{
ErrorLog errorLog = new ErrorLog();
errorLog.ErrorlogFile(ex.Message);
}
}
}
}