Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Creating a Windows Services in C#
WhatsApp
Husain Ahmedabadwala
May 09
2015
5.6
k
0
0
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
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;
using
System.Timers;
namespace
MyWinService
{
public
partial
class
Service1: ServiceBase
{
public
Service1()
{
InitializeComponent();
}
//************************************************************************************************************
//Initialize the timer
System.Timers.Timer timer =
new
System.Timers.Timer();
//************************************************************************************************************
//This method is used to raise event during start of service
protected
override
void
OnStart(
string
[] args)
{
//add this line to text file during start of service
TraceService(
"Start service"
);
//handle Elapsed event
timer.Elapsed +=
new
ElapsedEventHandler(OnElapsedTime);
//This statement is used to set interval to 30 Seconds (= 30,000 milliseconds)
timer.Interval = 30000;
//enabling the timer
timer.Enabled =
true
;
}
//************************************************************************************************************
//This method is used to stop the service
protected
override
void
OnStop()
{
timer.Enabled =
false
;
TraceService(
"Stopping service"
);
}
//************************************************************************************************************
private
void
OnElapsedTime(
object
source, ElapsedEventArgs e)
{
TraceService(
"Another entry at "
+ DateTime.Now);
}
//************************************************************************************************************
private
void
TraceService(
string
content)
{
//set up a filestream
FileStream fs =
new
FileStream(@
"d:\Service1.txt"
, FileMode.OpenOrCreate, FileAccess.Write);
//set up a streamwriter for adding text
StreamWriter sw =
new
StreamWriter(fs);
//find the end of the underlying filestream
sw.BaseStream.Seek(0, SeekOrigin.End);
//add the text
sw.WriteLine(content);
//add the text to the underlying filestream
sw.Flush();
//close the writer
sw.Close();
}
//************************************************************************************************************
}
}
Windows Service
Create Service in Windows