3

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)

Aliostad
  • 80,612
  • 21
  • 160
  • 208
Nicholas Murray
  • 13,305
  • 14
  • 65
  • 84

2 Answers2

6

You need to start a Foreground thread to keep process from exiting.

This is only achieved by creating new Thread. A Timer works as a background thread. See update below!

See my answer here:

Best use of Windows Service for repeating a program call


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()
        {
           // ...
        }
     }

UPDATE

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.

Community
  • 1
  • 1
Aliostad
  • 80,612
  • 21
  • 160
  • 208
2

Take a look into your system event log (Event Viewer). I'm sure some error occurred and that is why your service automatically stopped.

Possible problem is that your service cannot find your app.config (make sure it's named yoursvcname.exe.config). For test try to put your config file in "C:\WINDOWS\system32\".

EDIT

By seeing your event log error, i think that you are trying to access Event log from your code and you don't have required permissions or specified event log source is not accessible for some reason.

EDIT 2

Or take a look at this answers: System.Security.SecurityException when writing to Event Log

(Give NetworkService read permission on the EventLog/Security key)

Community
  • 1
  • 1
HABJAN
  • 9,212
  • 3
  • 35
  • 59
  • @HABJAN - putting files in `%windir%\system32` is almost *always* the wrong thing to do. The `svcname.exe.config` file, if there is one, should be in the same directory (usually `%programfiles%\VENDOR_NAME\SERVICE_NAME`) as the service. – Rob Apr 13 '11 at 12:55
  • @Nicholas Murray: is your code trying to access EventLog (read or write events) ? If yes then that means you dont have required permission. – HABJAN Apr 13 '11 at 12:56
  • @Rob: i agree, i suggested that only for test, to see and get some conclusions where the error is. – HABJAN Apr 13 '11 at 12:57
  • @Habjan - I removed any writes to the event log – Nicholas Murray Apr 13 '11 at 12:59
  • @Nicholas Murray: I'm sure you are accessing your event log from somewhere. The error says: "The source was not found, but some or all event logs could not be searched. Inaccessible logs" – HABJAN Apr 13 '11 at 13:01
  • @Habjan - I moved the config to C:\WINDOWS\system32 directory and no joy – Nicholas Murray Apr 13 '11 at 13:04
  • @Nicholas Murray: Can you please check again for errors in your event log? – HABJAN Apr 13 '11 at 13:05
  • @Habjan - I only write to Log.txt file – Nicholas Murray Apr 13 '11 at 13:07
  • @Habjan - still the same message – Nicholas Murray Apr 13 '11 at 13:10
  • @Nicholas Murray: I edited my answer, take a look at: http://stackoverflow.com/questions/1274018/system-security-securityexception-when-writing-to-event-log – HABJAN Apr 13 '11 at 13:12
  • @Habjan - coming full circle now, as I was unable to add the user as per the geekswithblogs I removed the writes to eventlog as I received the message An object named "NetworkService" cannot be found. Check the selected object types and location for accuracy and ensure that you typed the object name correctly, or remove this object from the selection. – Nicholas Murray Apr 13 '11 at 13:14
  • @Habjan - I right clicked on the service and changed the Log On setting to Local System Account and it now runs without that message. Would this have affected the Event Logging as well? – Nicholas Murray Apr 13 '11 at 13:28
  • @Habjan -- thanks it seems like it was an issue with accessing the interval value. – Nicholas Murray Apr 14 '11 at 11:30