C
C#2y ago
Hercules

❔ Getting started with windows service - onStart won't work. I am using VS 22.

I have this sample code trying to print to my event viewer. But this won't hit Onstart or give me the right sources in eventView its still "service1" as by default.
public partial class Worker : ServiceBase
{
Timer timer;
private int eventId = 1;
EventLog eventLog;
public Worker()
{
InitializeComponent();
eventLog = new EventLog();
if (!EventLog.SourceExists("Alexander"))
{
EventLog.CreateEventSource(
"Alexander", "AlexandersLog");
}
eventLog.Source = "Alexander";
eventLog.Log = "AlexandersLog";

timer = new Timer();
timer.Interval = 5000;
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();
}

protected override void OnStart(string[] args)
{
eventLog.WriteEntry("Service onStart - final");
}

protected override void OnStop()
{
EventLog.WriteEntry("Service OnStop - final");

}

public void OnTimer(object sender, ElapsedEventArgs args)
{
// TODO: Insert monitoring activities here.
eventLog.WriteEntry("Monitoring the System", EventLogEntryType.Information, eventId++);
}
}
public partial class Worker : ServiceBase
{
Timer timer;
private int eventId = 1;
EventLog eventLog;
public Worker()
{
InitializeComponent();
eventLog = new EventLog();
if (!EventLog.SourceExists("Alexander"))
{
EventLog.CreateEventSource(
"Alexander", "AlexandersLog");
}
eventLog.Source = "Alexander";
eventLog.Log = "AlexandersLog";

timer = new Timer();
timer.Interval = 5000;
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();
}

protected override void OnStart(string[] args)
{
eventLog.WriteEntry("Service onStart - final");
}

protected override void OnStop()
{
EventLog.WriteEntry("Service OnStop - final");

}

public void OnTimer(object sender, ElapsedEventArgs args)
{
// TODO: Insert monitoring activities here.
eventLog.WriteEntry("Monitoring the System", EventLogEntryType.Information, eventId++);
}
}
https://codeshare.io/dw8mzK
1 Reply
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server