This is my main:
static class Program
{
static void Main()
{
//Debugger.Launch();
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
And this is my Service1() code:
public partial class Service1 : ServiceBase
{
public Service1()
{
Thread messageThread = new Thread(new ThreadStart(Messaggi.Check));
messageThread.Start();
bool checkGruppoIndirizzi = true;
for (; ; )
{
SediOperative.Check();
Autisti.Check();
AutistiVeicoli.Check();
StatiVega.Check();
int res = Ordini.Check();
if (res == 0) AssegnazioniVega.Check();
Thread.Sleep(10000);
}
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
First thing is I don't know if launching two threads in that way is a good thing to do, but the real problem is the program run fine inside Visual Studio but after installation (I've created a setup project using InstallShield) I try to start my service from the windows service panel and I get:
Error 1053: The service did not respond to the start or control request in a timely fashion
The problem you have is that your service will be started sucessfully after the susyem has called the Start method and it has sucessfully returned. Given that you have an infinite loop in the constructor, the system is saying to itself something like "Can't even create the this let alone call start. I'm giving up.'
Your code should be refactored along these lines:
public partial class Service1 : ServiceBase
{
public Service1()
{
}
private Thread messageThread;
private Thread otherThread;
private bool stopNow;
protected override void OnStart(string[] args)
{
this.stopNow = false;
this.messageThread = new Thread(new ThreadStart(Messaggi.Check));
this.messageThread.Start();
this.otherThread = new Thread(new ThreadStart(this.StartOtherThread));
this.otherThread.Start();
}
private void StartOtherThread()
{
bool checkGruppoIndirizzi = true;
while (this.stopNow == false)
{
SediOperative.Check();
Autisti.Check();
AutistiVeicoli.Check();
StatiVega.Check();
int res = Ordini.Check();
if (res == 0) AssegnazioniVega.Check();
for (int 1 = 0; i < 10; i++)
{
if (this.stopNow)
{
break;
}
Thread.Sleep(1000);
}
}
}
}
protected override void OnStop()
{
this.stopNow = true;
this.messageThread.Join(1000);
this.otherThread.Join(1000);
}
}
And yes, starting stuff on Threads is exactly the way to do it! You'll have to have some way of stopping them in the Stop() method. (The code above is air code so don't trust it.) for the 'otherThread' I've got it checking a bool and exiting when the bool is set. the thread.Join is just a tidy-up which isn't strictly necessary, but is good housekeeping I think.
Cheers -
Related
I've been building out a service that processes files using a Queue<string> object to manage the items.
public partial class BasicQueueService : ServiceBase
{
private readonly EventWaitHandle completeHandle =
new EventWaitHandle(false, EventResetMode.ManualReset, "ThreadCompleters");
public BasicQueueService()
{
QueueManager = new Queue<string>();
}
public bool Stopping { get; set; }
private Queue<string> QueueManager { get; }
protected override void OnStart(string[] args)
{
Stopping = false;
ProcessFiles();
}
protected override void OnStop()
{
Stopping = true;
}
private void ProcessFiles()
{
while (!Stopping)
{
var count = QueueManager.Count;
for (var i = 0; i < count; i++)
{
//Check the Stopping Variable again.
if (Stopping) break;
var fileName = QueueManager.Dequeue();
if (string.IsNullOrWhiteSpace(fileName) || !File.Exists(fileName))
continue;
Console.WriteLine($"Processing {fileName}");
Task.Run(() =>
{
DoWork(fileName);
})
.ContinueWith(ThreadComplete);
}
if (Stopping) continue;
Console.WriteLine("Waiting for thread to finish, or 1 minute.");
completeHandle.WaitOne(new TimeSpan(0, 0, 15));
completeHandle.Reset();
}
}
partial void DoWork(string fileName);
private void ThreadComplete(Task task)
{
completeHandle.Set();
}
public void AddToQueue(string file)
{
//Called by FileWatcher/Manual classes, not included for brevity.
lock (QueueManager)
{
if (QueueManager.Contains(file)) return;
QueueManager.Enqueue(file);
}
}
}
Whilst researching how to limit the number of threads on this (I've tried a manual class with an incrementing int, but there's an issue where it doesn't decrement properly in my code), I came across TPL DataFlow, which seems like its a better fit for what I'm trying to achieve - specifically, it allows me to let the framework handle threading/queueing, etc.
This is now my service:
public partial class BasicDataFlowService : ServiceBase
{
private readonly ActionBlock<string> workerBlock;
public BasicDataFlowService()
{
workerBlock = new ActionBlock<string>(file => DoWork(file), new ExecutionDataflowBlockOptions()
{
MaxDegreeOfParallelism = 32
});
}
public bool Stopping { get; set; }
protected override void OnStart(string[] args)
{
Stopping = false;
}
protected override void OnStop()
{
Stopping = true;
}
partial void DoWork(string fileName);
private void AddToDataFlow(string file)
{
workerBlock.Post(file);
}
}
This works well. However, I want to ensure that a file is only ever added to the TPL DataFlow once. With the Queue, I can check that using .Contains(). Is there a mechanism that I can use for TPL DataFlow?
Your solution with Queue works only if file goes into your service twice in a small period of time. If it came again in, say, few hours, queue will not contain it, as you Dequeue it from there.
If this solution is expected, then you may use a MemoryCache to store file paths being already handled, like this:
using System.Runtime.Caching;
private static object _lock = new object();
private void AddToDataFlow(string file)
{
lock (_lock)
{
if (MemoryCache.Default.Contains(file))
{
return;
}
// no matter what to put into the cache
MemoryCache.Default[file] = true;
// we can now exit the lock
}
workerBlock.Post(file);
}
However, if your application must run for a long time (which service is intended to do), you'll eventually run out of memory. In that case you probably need to store your file paths in database or something, so even after restarting the service your code will restore the state.
You can check it inside of DoWork.
You have to save in Hash already works items and check current filename doesn't exist in hash.
I've code which starts depending whether the underlying application runs in console services instead of threads for the tasks. Here is a small cut of the main method:
//ANSAR BANK THREAD
Thread AnsarBankThread = new Thread(Ansar);
Console.WriteLine("Start The AnsarBankThread");
AnsarBankThread.Start();
//MELLAT BANK THREAD
Thread MellatBankThread = new Thread(Mellat);
Console.WriteLine("Start The MellatBankThread");
MellatBankThread.Start();
This is the code which will be executed:
static void Ansar()
{
var AnsarBank1 = new AnsarBank();
if (Environment.UserInteractive)
{
AnsarBank1.Start();
}
else
{
var servicesToRun = new ServiceBase[]{ AnsarBank1 };
ServiceBase.Run(servicesToRun);
}
}
static void Mellat()
{
var MellatBank1 = new MellatBank();
if (Environment.UserInteractive)
{
MellatBank1.Start();
}
else
{
var servicesToRun = new ServiceBase[]{ MellatBank1 };
ServiceBase.Run(servicesToRun);
}
}
and this is my AnsarBank service code:
protected override void OnStart(string[] args)
{
var timer = new System.Timers.Timer(5000); // fire every 30 second
timer.Elapsed += OnElapsedTime;
timer.Enabled = true;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
File.WriteAllText(#"d:\Temp\Ansar.txt", "Ansar Bank Writer\n");
}
public void Start()
{
OnStart(new string[0]);
}
And this is my MellatBank Service:
protected override void OnStart(string[] args)
{
var timer = new System.Timers.Timer(5000); // fire every 30 second
timer.Elapsed += OnElapsedTime;
timer.Enabled = true;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
File.WriteAllText(#"d:\Temp\MellatBank.txt", "Mellat Bank writer\n");
}
public void Start()
{
OnStart(new string[0]);
}
However, if I run the code there will be only the file Ansar.txt created and the file MellatBank.txt is missing!
Can someone encounter the problem in my code please? I would appreciate any help!
Chnage code to this:
System.Timers.Timer personalTimer = null;
public AnsarBank()
{
personalTimer = new System.Timers.Timer(5000);
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//var timer = new System.Timers.Timer(5000); // fire every 30 second
personalTimer.Elapsed += OnElapsedTimeAnsar;
personalTimer.Enabled = true;
}
but so not work.
What's the problem?
1. Variable goes out of scope:
Thanks to #MatthewWatson: I also suggest moving the timer variable outside of the method right into the class. The timer object can be garbage collected directly because the garbage collector doesn't see that it's used any further.
Why thinks the gc that the variable isn't used anymore?
Simply because you created it in the method. It's local and because the class itself hasn't any reference to it there isn't any hint for the gc that it's needed further!
This should be true after I looked to this question.
Solution to this in sample code:
class SomeClass {
System.Timers.Timer personalTimer = null; //Timer is now garbage collected after the object of SomeClass goes out of scope!
SomeClass() {
personalTimer = new Syste.Timers.Timer(30000) // Now every 30 seconds!
}
protected override void OnStart(string[] args)
{
personalTimer.Elapsed += OnElapsedTime;
personalTimer.AutoReset = true; //Add this line to keep continuos activation
personalTimer.Enabled = true;
}
....
}
2.File access problems
After I tried your code I encountered exceptions because the path may not exist. So I changed the code to create a path before the creation of a file. Also I added checks whether file exists and if so that text will be applied to the file. The old solution replaced the file everytime. This works for me fine. I don't know what you've done with InitializeComponents(...) this seems to be gui stuff, so I don't know.
Change your code in the service classes to following please:
namespace WebService
{
partial class MellatBank : ServiceBase
{
System.Timers.Timer personalTimer = null;
public MellatBank()
{
personalTimer = new System.Timers.Timer(1000);
this.ServiceName = "MellatBankService";
}
protected override void OnStart(string[] args)
{
personalTimer.Elapsed += OnElapsedTimeMellat;
personalTimer.AutoReset = true; //Add this line to keep continuos activation
personalTimer.Enabled = true;
//var timer = new System.Timers.Timer(5000); // fire every 30 second
//personalTimer.Elapsed += OnElapsedTimeMellat;
//personalTimer.Enabled = true;
}
private void OnElapsedTimeMellat(object source, ElapsedEventArgs e)
{
try
{
if (!Directory.Exists(#"D:\Temp"))
Directory.CreateDirectory(#"D:\Temp\");
if (!File.Exists(#"D:\Temp\MellatBank.txt"))
{
var f = File.CreateText(#"D:\Temp\MellatBank.txt");
f.Write(#"D:\Temp\MellatBank.txt", "Mellat Bank writer\n");
f.Close();
}
else
{
var f = File.AppendText(#"D:\Temp\MellatBank.txt");
f.Write("Mellat Bank writer\n");
f.Close();
}
}
catch (System.Exception ex)
{
Console.Error.WriteLine("IO EXCEPTION: {0}", ex.ToString());
}
}
public void Start()
{
OnStart(new string[0]);
}
protected override void OnStop()
{
Console.Out.WriteLine("ended!");
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
}
namespace WebService
{
partial class AnsarBank : ServiceBase
{
System.Timers.Timer personalTimer = null;
public AnsarBank()
{
personalTimer = new System.Timers.Timer(1000);
this.ServiceName = "AnsarBankService";
}
protected override void OnStart(string[] args)
{
personalTimer.Elapsed += OnElapsedTimeAnsar;
personalTimer.AutoReset = true; //Add this line to keep continuos activation
personalTimer.Enabled = true;
//var timer = new System.Timers.Timer(5000); // fire every 30 second
//personalTimer.Elapsed += OnElapsedTimeAnsar;
//personalTimer.Enabled = true;
}
private void OnElapsedTimeAnsar(object source, ElapsedEventArgs e)
{
try
{
if (!Directory.Exists(#"D:\Temp"))
Directory.CreateDirectory(#"D:\Temp\");
if (!File.Exists(#"D:\Temp\Ansar.txt"))
{
var f = File.CreateText(#"D:\Temp\Ansar.txt");
f.Write(#"D:\Temp\Ansar.txt", "Ansar Bank writer\n");
f.Close();
}
else
{
var f = File.AppendText(#"D:\Temp\Ansar.txt");
f.Write("Ansar Bank Writer\n");
f.Close();
}
}
catch (System.Exception ex)
{
Console.Error.WriteLine("IO EXCEPTION: {0}", ex.ToString());
}
}
public void Start()
{
OnStart(new string[0]);
}
protected override void OnStop()
{
Console.Out.WriteLine("ended!");
}
}
}
Edit:
After viewing your code I saw that your services only run as long as your application runs. So your services may have been stopped before they could write anything which would explain your problem too.
PS:
Asker please practice the basics of Object Oriented Programming (OOP) again if you don't know what class fields are.
I try to create a windows service which automatically startsup.
I am able to install and deinstall the service. If I try to start it, I get following error message: "Der Dienst antwortete nicht rechtzeitig auf die Start- oder Steueranfrage". (I try to translate) "The service don't respont in time on start or control request".
Here is my poor code
public class LisaServerService: System.ServiceProcess.ServiceBase
{
private Program lisaServerServiceProgram;
public static string LisaServiceName = "LISA-ServerService";
[STAThread]
public static void Main(string[] args)
{
LisaServerService lisaServerService = new LisaServerService();
if (Environment.UserInteractive)
{
lisaServerService.OnStart(args);
Console.WriteLine("I am a service. Normally you can't see the console... just ignore me");
Console.ReadLine();
lisaServerService.OnStop();
}
else
{
ServiceBase.Run(lisaServerService);
}
}
public LisaServerService()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.CanShutdown = true;
this.ServiceName = "LISA - ServerService";
this.CanPauseAndContinue = true;
this.lisaServerServiceProgram = new Program();
}
protected override void OnStart(string[] args)
{
lisaServerServiceProgram.Start(null);
base.OnStart(args);
}
protected override void OnStop()
{
lisaServerServiceProgram.Stop();
base.OnStop();
}
protected override void OnShutdown()
{
OnStop();
base.OnShutdown();
}
}
Program.cs
public class Program
{
public Program()
{
Logger.LogLevel = LogLevel.Information;
Logger.LogRange = LogRange.Write;
Logger.Log("Logger initialized");
}
public void Start(string[] args)
{
DatabaseHandler.StartDatabase();
NetworkHandler.StartNetwork();
Logger.Log("Service started");
}
if I run the service as a console program, it works fine.
So the db connection + logger are working fine too. (Also within < 10ms)
If you're running the service in interactive mode it's waiting for the console here:
if (Environment.UserInteractive)
{
lisaServerService.OnStart(args);
Console.WriteLine("I am a service. Normally you can't see the console... just ignore me");
Console.ReadLine();
...
That is likely preventing the service from responding properly to indicate it is started.
I'm building a Windows Service using System.Timers.Timer. The tasks computed by the Timer's delegate can take from several seconds to several minutes. I would like to make sure that, when the service is stopped, all delegated threads currently running complete before being disposed.
Here is the code, however it does not do what I expect, as currently running threads never complete if the Windows Service is stopped while they are running.
public abstract class AgentServiceBase : ServiceBase
{
private System.ComponentModel.IContainer components = null;
private System.Timers.Timer _Timer;
private string _logPath;
private const int MAXNUMBEROFTHREADS = 10;
protected int interval = 25000;
protected int numberOfAllowedThreads = 2;
public AgentServiceBase()
{
this.InitializeComponent();
this._logPath = (Path.GetDirectoryName(Assembly.GetAssembly(this.GetType()).CodeBase)).Substring(6).Replace("/", #"\");
}
protected override void OnStart(string[] args)
{
if (args.Length > 0)
{
int.TryParse(args[0], out interval);
}
if (args.Length > 1)
{
int.TryParse(args[1], out numberOfAllowedThreads);
if (numberOfAllowedThreads > MAXNUMBEROFTHREADS)
{
numberOfAllowedThreads = MAXNUMBEROFTHREADS;
}
if (numberOfAllowedThreads == 1)
{
numberOfAllowedThreads = 2;
}
}
ThreadPool.SetMaxThreads(numberOfAllowedThreads, numberOfAllowedThreads);
this._Timer = new System.Timers.Timer();
this._Timer.Elapsed += new ElapsedEventHandler(PollWrapper);
this._Timer.Interval = this.interval;
this._Timer.Enabled = true;
}
protected override void OnStop()
{
this._Timer.Enabled = false;
Process currentProcess = Process.GetCurrentProcess();
foreach (Thread t in currentProcess.Threads)
{
t.Join();
}
}
/// <summary>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Agent Service - Johnhenry";
}
private void PollWrapper(object sender, ElapsedEventArgs e)
{
try
{
this.Poll(sender, e);
}
catch (Exception exception)
{
string message = this.GetType().FullName + " - Windows Service Exception\n";
message += exception.GetNestedExceptionInSingleStringOutput();
FileHelper.Log(message, this._logPath, "exception", FileHelper.LogFileNameChangeFrequency.DAYLY);
}
}
protected abstract void Poll(object sender, ElapsedEventArgs e);
}
Many thanks,
Giuseppe
UPDATE:
After few different attempts with counting the current process's own threads I eventually settled with a simpler solution which is using a counter of the threads the timer had initiated and are still running. Based on that I call the Sleep on the main thread and issue a RequestAdditionalTime until all threads have ended.
Following the revised 2 methods:
protected override void OnStop()
{
this._Timer.Enabled = false;
while (numberOfRunningThreads > 0)
{
this.RequestAdditionalTime(1000);
Thread.Sleep(1000);
}
}
private void PollWrapper(object sender, ElapsedEventArgs e)
{
numberOfRunningThreads++;
try
{
this.Poll(sender, e);
}
catch (Exception exception)
{
string message = this.GetType().FullName + " - Windows Service Exception\n";
message += exception.GetNestedExceptionInSingleStringOutput();
FileHelper.Log(message, this._logPath, "exception", FileHelper.LogFileNameChangeFrequency.DAYLY);
}
finally
{
numberOfRunningThreads--;
}
}
You can achieve that by calling RequestAdditionalTime as long as your threads haven't finished the work yet in your implementation of OnStop inside the loop (before and/or after the call to Join()).
BUT BEWARE that Windows can get impatient and decide to kill your Windows Service - for example during shutdown...
For more information see the MSDN reference at http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.aspx
My question is that is this the best practice to do this. Couldn't find any good examples. I have following code in file created by VS2005:
public partial class ObjectFolder : ServiceBase
{
protected override void OnStart(string[] args)
{
ObjectFolderApp.Initialize();
ObjectFolderApp.StartMonitorAndWork();
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop yourservice.
}
}
then:
class ObjectFolderApp
{
public static bool Initialize()
{
//all init stuff
return true;
}
public static void StartMonitorAndWork()
{
Thread worker = new Thread(MonitorAndWork);
worker.Start();
}
private static void MonitorAndWork()
{
int loopTime = 60000;
if (int.TryParse(_cfgValues.GetConfigValue("OfWaitLoop"), out loopTime))
loopTime = 1000 * loopTime;
while (true)
{
/* create+open connection and fill DataSet */
DataSet ofDataSet = new DataSet("ObjectFolderSet");
using (_cnctn = _dbFactory.CreateConnection())
{
_cnctn.Open();
//do all kinds of database stuff
}
Thread.Sleep(loopTime);
}
}
}
Re-hashing my answer from this question, the recommended way is to use a timer and the following code:
public class MyService : ServiceBase
{
private Timer workTimer; // System.Threading.Timer
protected override void OnStart(string[] args)
{
workTimer = new Timer(new TimerCallback(DoWork), null, 5000, 5000);
base.OnStart(args);
}
protected override void OnStop()
{
workTimer.Dispose();
base.OnStop();
}
private void DoWork(object state)
{
RunScheduledTasks(); // Do some work
}
}
Simple!
Note that the Timer type being used is System.Threading.Timer, same as Justin specifies.
Use a System.Threading.Timer to fire the process off at the scheduled interval.