Hi

I am working on windows services. i can bale to run the service for every 1 min. I creating multi thread. but i required the service to run in single thread. can any one please help me to fix my issue.

Code

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

namespace SchedulerServiceT
{
public partial class SchedulerService : ServiceBase
{
public SchedulerService()
{
InitializeComponent();
}
TestWriteFile process;
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
base.OnStart(args);
process = new TestWriteFile();
process.StartProcess();
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
base.OnStop();
process.StopProcess();
}
public class TestWriteFile
{
public static bool Shutdown = false;
Thread ServiceThread;
public static void WriteCurrentTimewithService()
{
while (Shutdown == false)
{
String str = AppDomain.CurrentDomain.BaseDirectory+"\\run.bat";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
//Run this code for every 1 Minutes or stop if service is stoped
Thread.Sleep(60000);
}
}
public void StartProcess()
{
ServiceThread = new Thread(new ThreadStart(WriteCurrentTimewithService));
ServiceThread.Start();
}
public void StopProcess()
{
Shutdown = true;
ServiceThread.Join();
}
}
}
}

So what's the problem exactly? Looks like you spin up one thread and are your way.

You should be aware, that Thread.Sleep(60000). Once you hit that, the thread it's running on is going to sleep for a minute, and any command you try to send it, won't be acknoweldged until you come out of the sleep. I would advise using like a for loop, and sleeping for like 5 ms increments, and checking the flag (and then once you have incremented to pass the 1 min part you go back to the top of your Shutdown == false while loop).

Now that being said, if I am looking at your code correctly, because of this massive sleep, you might have trouble accessing that "Shutdown" property externally. The sleep might brick the whole thing ... BUT, I can't say for sure, I'd have to test that myself to be sure, it's just a guess.

Thanks JOSheaIV

Instead of trying to time your code with a sleep (giving the possible issues that arise, mentioned above), you might want to look into Quartz for .NET. I've used it in several service scenarios and is very stable and easy to use.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.