I have created a C# windows service that should send some emails but when I start the service I receive the message 'the service on the local started and then stopped'... 'some services stop automatically if they have no work to do'
Why would this be?
namespace EmailService
{
public partial class EmailService : ServiceBase
{
private System.Timers.Timer _timer = null;
private DateTime _lastRun = DateTime.Now;
private int _timerIntervalValue;
public EmailService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["Timer"]))
{
throw new Exception("The timer value is not set in the app.config.");
}
else
{
_timerIntervalValue = Convert.ToInt32(ConfigurationManager.AppSettings["Timer"]);
}
_timer = new System.Timers.Timer(_timerIntervalValue);
_timer.Elapsed += OnTimedEvent;
_timer.Interval = Convert.ToInt32(_timerIntervalValue);
_timer.Enabled = true;
}
protected override void OnStop()
{
_timer.Stop();
_timer.Dispose();
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
Email email = new Email();
email.ProcessEmails();
_lastRun = DateTime.Now;
_timer.Start();
}
}
}
Event Log entry
Service cannot be started. System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security. at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly) at System.Diagnostics.EventLog.SourceExists(String source, String machineName) at System.Diagnostics.EventLog.SourceExists(String source)
You need to start a Foreground thread to keep process from exiting.
This is only achieved by creating new Thread. A See update below!Timer works as a background thread.
See my answer here:
This is a VERY SIMPLISTIC approach:
public partial class EmailService : ServiceBase
{
Thread _thread = new Thread(DoAlways)
protected override void OnStart(string[] args)
{
_thread.Start();
}
private void DoAlways()
{
while()
{
// ...
}
}
Timer of a type System.Timers.Timer uses System.Threading.Timer which in turn uses a native WIN32 timer.
I did compile and install your service on my machine (XP) and it just worked. Service started with no problem.I suggest that you hard-code the interval value to see if it works since I suspect it gets a value of zero hence timer never initialised.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With