I have a simple Windows Service application that can be run as a service or application started by user double-click. The problem is that I have no logs from OnStop event handler. There is no problem with OnStart handler. Why I cannot see any logs from OnStop?
public partial class TransmedicomCentralService : ServiceBase
{
TransmedicomCentralWorker serverThread;
public TransmedicomCentralService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// konfiguracja loggera
GostcompUtils.Logger.Level = GostcompUtils.LoggerLevel.Trace;
GostcompUtils.Logger.FileName = "nowyPlikLogow.txt";
GostcompUtils.Logger.Targets = new List<GostcompUtils.LoggerTarget>() { GostcompUtils.LoggerTarget.File };
base.OnStart(args);
GostcompUtils.Logger.Log("Rozruch serwisu", GostcompUtils.LoggerLevel.Info);
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
serverThread = new TransmedicomCentralWorker();
GostcompUtils.Logger.Log("Serwis uruchomiono", GostcompUtils.LoggerLevel.Info);
}
protected override void OnStop()
{
base.OnStop();
GostcompUtils.Logger.Log("Zatrzymywanie serwisu", GostcompUtils.LoggerLevel.Info);
serverThread.Dispose();
GostcompUtils.Logger.Log("Serwis zatrzymano", GostcompUtils.LoggerLevel.Info);
}
public static void Main(string[] args)
{
TransmedicomCentralService service = new TransmedicomCentralService();
if (Environment.UserInteractive)
{
service.OnStart(args);
Console.WriteLine("Press any key to stop program");
Console.Read();
service.OnStop();
}
else
{
ServiceBase.Run(service);
}
}
}
Related
This question already has answers here:
Better way to constantly run function periodically in C#
(3 answers)
Closed 2 years ago.
Id like to build a windows Service in C#.
This service needs to be run periodically like every 10s.
Questions:
What is the difference between Timers.timer and Threading.timer?
How can I call CheckingThings with parameters?
If i run this code, it does invoke CheckingThings more than once every second like declared in here:
_timer = new Timer(new TimerCallback(CheckingThings), autoEvent, 5000, 1000);
Here is what i've got so far:
public partial class WindowsService1 : ServiceBase
{
// Logging
private static Serilog.Core.Logger _logEvent;
public WindowsService1()
{
InitializeComponent();
}
public void OnDebug() {
OnStart(null);
}
protected override void OnStart(string[] args)
{
//Logging
try {
_logEvent = new LoggerConfiguration()
.WriteTo.File(AppDomain.CurrentDomain.BaseDirectory + #"Logs\Logfile.txt", rollingInterval: RollingInterval.Month)
.CreateLogger();
}
catch (Exception e)
{
_logEvent.Error("The logging service is not working as expected: {errorMsg}", e);
}
try
{
// initializing some data here
var autoEvent = new AutoResetEvent(true);
while (true)
{
_timer = new Timer(new TimerCallback(CheckingThings), autoEvent, 5000, 1000);
}
}
catch (Exception e) {
_logEvent.Error("An error occured while initializing service: {0}", e);
}
}
private static void CheckingThings(object stateInfo)
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
//These things needs to run periodically every 10s
}
protected override void OnStop()
{
_logEvent.Information("Stopping Service ...");
}
}
Here's a skeleton for a service class that does something every minute, using a System.Timers.Timer:
public partial class XService : ServiceBase
{
private Timer _minute = new Timer(60000);
public XService()
{
InitializeComponent();
_minute.Elapsed += Minute_Elapsed;
}
//this is async because my 'stuff' is async
private async void Minute_Elapsed(object sender, ElapsedEventArgs e)
{
_minute.Stop();
try
{
//stuff
}
catch (Exception ex)
{
//log ?
}
finally
{
_minute.Start();
}
}
protected override void OnStart(string[] args)
{
_minute.Start(); //this or..
Minute_Elapsed(null, null); //..this, if you want to do the things as soon as the service starts (otherwise the first tick will be a minute after start is called
}
...
I typically stop my timers while I do my thing - no point starting a job that takes 10 minutes and then another one a minute later, hence the stop/try/finally/start pattern
Edit:
Here's the tail part of the class and how it's started/launched both in debug (inside visual studio) and in release (as an installed windows service):
//just an adapter method so we can call OnStart like the service manager does, in a debugging context
public void PubOnStop()
{
OnStop();
}
}// end of XService class
static void Main(string[] args)
{
#if DEBUG
new XService().PubStart(args);
Thread.Sleep(Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new XService()
};
ServiceBase.Run(ServicesToRun);
#endif
}
I have created a windows service using .Net framework 4.7 with C# as the language. This service basically fetches computer hardware information (CPU usage) and writes it to a log file (using log4net). After compiling the service in release mode, when i installed it using installutil, the service is created and upon starting the service, a file with same name as 'exe' file with extension of 'sys' gets created frequently and deleted as well. Now when i stop the service, it is no longer created. I have created few windows services in the past using .Net but never encountered such behavior.
Program.cs
static void Main()
{
#if DEBUG
Service serv = new Service();
serv.StartIt();
Thread.Sleep(20000);
serv.StopIt();
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service()
};
ServiceBase.Run(ServicesToRun);
#endif
}
Service.cs
Timer timer = null;
public Service()
{
InitializeComponent();
timer = new Timer(1000);
timer.Elapsed += Timer_Elapsed;
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
SystemInfo si = new SystemInfo();
si.GetSystemInfo();
}
#if DEBUG
public void StartIt()
{
timer.Start();
}
public void StopIt()
{
timer.Stop();
}
protected override void OnStart(string[] args)
{ }
protected override void OnStop() { }
#else
protected override void OnStart(string[] args)
{
timer.Start();
}
protected override void OnStop()
{
timer.Stop();
}
#endif
Note: I am using OpenHardwareMonitor library to collect hardware information.
Link to the problem description
I have started building up the windows service in the c# language. And i want to implement the timer feature inside it. But for some reason, the DoIt timer event handler is not getting fired during the debugging and i am not getting any exception also. I am trying to debug the windows service using Debug->Start new instance.
The line TraceLog.WriteTrace("Router Service Started"); does get hit and executed.
public partial class EntryPoint : ServiceBase
{
private const int TIMER_INTERVAL = 10000;
private System.Timers.Timer mvTimer = new System.Timers.Timer();
[MTAThread()]
[System.Diagnostics.DebuggerNonUserCode()]
public static void Main()
{
#if DEBUG
EntryPoint service = new EntryPoint();
service.Start();
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new EntryPoint()
};
ServiceBase.Run(ServicesToRun);
#endif
}
public EntryPoint()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
InitializeComponent();
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = (Exception)e.ExceptionObject;
if (ex != null)
{
Console.WriteLine(ex);
}
}
public void Start()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
TraceLog.SetTrace(ConfigurationManager.AppSettings["RouterTraceLog"]);
TraceLog.WriteTrace("Router Service Started");
mvTimer = new Timer();
mvTimer.Elapsed += new ElapsedEventHandler(DoIt);
try
{
mvTimer.Interval = TIMER_INTERVAL;
mvTimer.Enabled = true;
}
catch (Exception ex)
{
mvTimer.Interval = TIMER_INTERVAL;
TraceLog.WriteTrace(ex.Message);
}
}
private void DoIt(object sender, ElapsedEventArgs e)
{
TraceLog.WriteTrace("Inside DoIt :: " + DateTime.UtcNow.ToString());
}
protected override void OnStop()
{
mvTimer.Enabled = false;
TraceLog.WriteTrace("Router Service stopping");
}
Please suggest. I am missing something very small and not able to nail it down.
In debug mode, the application exits after the function OnStart finishes. There's nothing to stop the application from quitting.
What you need is add a Console.ReadLine(); to prevent the application from exiting.
#if DEBUG
EntryPoint service = new EntryPoint();
service.Start();
Console.ReadLine();
#else
You can read more at MSDN on How to: Debug Windows Service Applications
I have developed a Windows Service whose task is actually to start a host with particular url and port. Below is what I have now.
Program.cs
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new WindowsDxService()
};
ServiceBase.Run(ServicesToRun);
}
ProjectInstaller.cs
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
}
WindowsDxService.cs
public partial class WindowsDxService : ServiceBase
{
public WindowsDxService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
var url = "http://127.0.0.1:9000";
using (var host = new NancyHost(new Uri(url)))
{
host.Start();
}
}
}
Configuration on serviceProcessInstaller1 and serviceInstaller1 in ProjectInstaller.cs [Design] file.
serviceProcessInstaller1
Account=LocalSystem
serviceInstaller1
StartType=Automatic
Library.cs
public class Library : NancyModule
{
public Library()
{
Get["/"] = parameters =>
{
return "Hello world";
};
Get["jsontest"] = parameters =>
{
var test = new
{
Name = "Guruprasad Rao",
Twitter="#kshkrao3",
Occupation="Software Developer"
};
return Response.AsJson(test);
};
}
}
Basically I followed this tutorial which actually shows how to do it with Console application which I succeeded though, but I wanted to have this as Windows Service which actually starts a host with specified port whenever the system starts. The service is started successfully and running but whenever I browse the url in the same system its not showing up the page, which means our basic This webpage is not available message. What else configuration I have to do so as to start the host? Hoping for a help.
You are disposing the host when you start your service. I would suggest something like this:
public partial class WindowsDxService : ServiceBase
{
private Host host;
public WindowsDxService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.host = new NancyHost(...)
this.host.Start();
}
protected override void OnStop()
{
this.host.Stop();
this.host.Dispose();
}
}
You'd probably find it a lot easier to write the service if you used TopShelf library.
I have a WCF service library (MyWCFService), which uses MEF to load plugins and hosted by Windows services (All .NET 4.0). I am now trying to run it in a new AppDomain and to enable ShadowCopyFiles in a hope that I can update plugins in the runtime. Here is the code in the Windows service project.
Program.cs
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
}
}
MyService.cs
public partial class MyService: ServiceBase
{
internal static ServiceHost MyServiceHost = null;
public MyService()
{
// this works but is deprecated..
AppDomain.CurrentDomain.SetShadowCopyFiles();
//this is not working.. DLLs still get locked. Require for a new AppDomain
//AppDomain.CurrentDomain.SetupInformation.ShadowCopyFiles = "true";
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if(MyServiceHost !=null)
{
MyServiceHost.Close();
}
try
{
MyServiceHost= new ServiceHost(typeof(MyWCFService));
MyServiceHost.Open();
}
catch(Exception)
{
}
}
protected override void OnStop()
{
if (MyServiceHost!= null)
{
MyServiceHost.Close();
MyServiceHost= null;
}
}
}
Is there any way of doing it? I have done a lot of search, but still don't know how to make it work with my current settings (or I just can't understand...)
I have tried to create a new AppDomain inside Main() and used
domain.DoCallBack(new CrossAppDomainDelegate(() => { ServiceBase.Run(ServicesToRun); })) to start the service but I can't start it and keep getting "Error 1053: The service did not respond to the start or control request in a timely fashion".
And then I tried to just enable Shadow copy for the current appdomain by setting AppDomain.CurrentDomain.SetupInformation.ShadowCopyFiles = "true"; in MyWCFService.cs just before InitializeComponent(); I can start the service but the dlls are still locked. however, if I use AppDomain.CurrentDomain.SetShadowCopyFiles(); (a deprecated method) to enable the shadow copy, everything works. I'm more confused.
OK, I ended up with creating a shell/proxy class inherited from MarshalByRefObject and start the service from there, and here is the code:
ServiceShell.cs
public class ServiceShell:MarshalByRefObject
{
internal static ServiceHost MyServiceHost = null;
public void Run()
{
if (MyServiceHost != null)
{
MyServiceHost.Close();
}
try
{
MyServiceHost = new ServiceHost(typeof(MyWCFService));
MyServiceHost.Open();
}
catch (Exception)
{
}
}
public void Stop()
{
if (MyServiceHost!= null)
{
MyServiceHost.Close();
MyServiceHost = null;
}
}
}
MyService.cs
public partial class MyService: ServiceBase
{
AppDomain domain;
ServiceShell runner;
public MyService()
{
var setup = new AppDomainSetup
{
ShadowCopyFiles = "true"
};
domain = AppDomain.CreateDomain("MyServiceHostDomain", AppDomain.CurrentDomain.Evidence, setup);
runner = (ServiceShell)domain.CreateInstanceAndUnwrap
(typeof(ServiceShell).Assembly.FullName, typeof(ServiceShell).FullName);
InitializeComponent();
}
protected override void OnStart(string[] args)
{
runner.Run();
}
protected override void OnStop()
{
runner.Stop();
AppDomain.Unload(domain);
}
}