How to run a task asynchronously using Windows Service C#

How to run a task asynchronously using Windows Service C#

If you need to run something, let’s say every 10 minutes or hours we can use C# to develop a Windows Service in Visual Studio and that will do the job for us.


1) Create a new project as Windows Service ‘ABC.MyWindowsService’
2) Add a new window library project (ABC.Execute) so that we can keep functionality, database classes separately
3) Add a new Execution handler class to ABC.Execute project and name is ExecutionHandler.cs
{
public class ExecutionHandler
{
private static string orgName = string.Empty;
private static string userName = string.Empty;
private static string password = string.Empty;
private static string strIntervalInMinutes = string.Empty;

public static void Execute()
{
orgName = ConfigurationManager.AppSettings[“orgName”].ToString();
userName = ConfigurationManager.AppSettings[“userName”].ToString();
password = ConfigurationManager.AppSettings[“password”].ToString();
strIntervalInMinutes = ConfigurationManager.AppSettings[“strIntervalInMinutes”].ToString();

double interval = 10; //by default one minute

if (strIntervalInMinutes!=null)
{
interval = double.Parse(strIntervalInMinutes);
}

try
{
while (true)
{

Debug.WriteLine(“CLIENT : Create EBiletServiceClient”);
{
//all code here
}
}
}
}
4) Above is the sample code we need to use for SQL connectivity – make sure SQL file exists in both Windows Service and Class library project
5) Add SQL folder and then .sql file to it and store sql query script in it
6) Also copy sql folder to ABC.MyWindowsService>Debug>Bin folder
7) Anything need adding to app.config in Windows Service project we also need same to app.config in Windows library project
8) Once all done then go to ABC.MyWindowsService>Program.cs
9) And add code below or similar to it
{
static class Program
{
///
/// The main entry point for the application.
///

static void Main()
{
System.Threading.Thread.Sleep(20000);

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyWindowsService()
};
ServiceBase.Run(ServicesToRun);
}
}
}
10) Also make sure you have added reference of Windows Library project to Windows Service project
11) Now compile the project and install Windows service using installutil in Developer Command prompt for Visual Studio

Comments are closed.