I have created a console application in C#. How can I program this application so that it will re-start itself after a crash?
If I understand your question correctly, you want to attempt to re-start a console app in the event of a crash. In C# console-apps the method defined as the entry point (usually static void main) is the root of the call stacks in the app. You essentially would need to call that method recursively. You will want to make sure that the app eventually fails if it is in some unintended or unrecoverable state.
For example in the main class:
static int retryCount;
const int numberOfRetries = 3;
static void Main(string[] args)
{
try
{
var theApp = new MyApplicationType(args);
theApp.StartMyAppLogic();
}
catch (ExpectedExceptionType expectThisTypeOfException)
{
thisMethodHandlesExceptions(expectThisTypeOfException);
}
catch (AnotherExpectedExceptionType alsoExpectThisTypeOfException)
{
thisMethodHandlesExceptions(alsoExpectThisTypeOfException);
}
catch (Exception unexpectedException)
{
if(retryCount < numberOfRetries)
{
retryCount++;
Main(args);
}
else
{
throw;
}
}
}
You can use a watchdog to process your monitor and restart it if crashed:
see: What's the best way to watchdog a desktop application?
You can use a windows service instead and set it's recovery options as indicated here: https://serverfault.com/questions/48600/how-can-i-automatically-restart-a-windows-service-if-it-crashes
You can use a scheduled task in task manager to start your application periodically , and set it to only start if previous run has ended:
https://support.microsoft.com/en-us/kb/323527
You could try something like this:
static void Main(string[] args)
{
try
{
// Application code goes here
}
catch (Exception)
{
var applicationPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
Process.Start(applicationPath);
Environment.Exit(Environment.ExitCode);
}
}
Basically, wrap all the code in a try/catch, and if any exceptions occur, the program will retrieve the .exe location with System.Reflection.Assembly.GetExecutingAssembly().Location; and then call Process.Start to run the application again.
You should control your console app from another application (watchdog, sheduler, procmon, servman, ...).
E.g. you can create your console app as a service and control it from service manager.
I created a Windows service application. It runs depending on the app settings which is included in the app.config file. It will be installed on different locations (networks, PCs) at the same time. Each location will need to set its own parameters in the app.config file. So I don't want it to run automatically after installation. By doing that each location users will be able to open configuration file and change it. Then they can start the service. But after that the service will run forever. Even when they restart the windows, it will run automatically after Windows opened.
Here is my installer class. It doesn't run automatically after installation. That's good. But if I run it manually and restart PC, when restart complete, it still waits to be started manually. What should I do?
public partial class MyServiceInstaller : System.Configuration.Install.Installer
{
ServiceInstaller _serviceInstaller = new ServiceInstaller();
ServiceProcessInstaller _processInstaller = new ServiceProcessInstaller();
string _serviceName = "MyService";
string _displayName = "My Service";
string _description = "My Service - Windows Service";
public MyServiceInstaller()
{
InitializeComponent();
this.BeforeInstall += new InstallEventHandler(MyServiceInstaller_BeforeInstall);
_processInstaller.Account = ServiceAccount.LocalSystem;
_serviceInstaller.StartType = ServiceStartMode.Automatic;
_serviceInstaller.Description = _description;
_serviceInstaller.ServiceName = _serviceName;
_serviceInstaller.DisplayName = _displayName;
Installers.Add(_serviceInstaller);
Installers.Add(_processInstaller);
}
protected override void OnCommitted(System.Collections.IDictionary savedState)
{
ServiceController sc = new ServiceController(_serviceName);
if (sc.Status != ServiceControllerStatus.Running)
{
TimeSpan timeout = TimeSpan.FromMilliseconds(10000);
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, timeout);
sc.Stop();
}
else
{
RestartService(10000);
}
}
private void RestartService(int timeoutMiliseconds)
{
ServiceController service = new ServiceController(_serviceName);
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMiliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMiliseconds - (millisec2 - millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
void MyServiceInstaller_BeforeInstall(object sender, System.Configuration.Install.InstallEventArgs e)
{
List<ServiceController> services = new List<ServiceController>(ServiceController.GetServices());
foreach (ServiceController s in services)
{
if (s.ServiceName == this._serviceInstaller.ServiceName)
{
ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
ServiceInstallerObj.Context = new System.Configuration.Install.InstallContext();
ServiceInstallerObj.Context = Context;
ServiceInstallerObj.ServiceName = _serviceName;
ServiceInstallerObj.Uninstall(null);
}
}
}
}
You can make this easier for yourself, by downloading the NuGet Package called TopShelf.
To summarize briefly, quoting from their page:
Topshelf is a framework for hosting services written using the .NET
framework. The creation of services is simplified, allowing developers
to create a simple console application that can be installed as a
service using Topshelf. The reason for this is simple: It is far
easier to debug a console application than a service. And once the
application is tested and ready for production, Topshelf makes it easy
to install the application as a service.
Your code already seems to be setting the startup type to Automatic.
Can you check the event log to see if your service is attempting to start automatically, but failing. This can happen if your service depends on another service which has not yet started.
You can use sc config after service start to modify start type.
eg.
sc config yourservicename start=auto
Or you can use ChangeServiceConfig.
I have written a code to restart my windows service but it never works properly. Service is able to stop but never start again. My Project is self hosted WCF service inside a Windows Service. below is the code.
Restart Method
public static void RestartService(string serviceName)
{
try
{
ServiceController svc = new ServiceController(serviceName);
if (svc.Status == ServiceControllerStatus.Running) svc.Stop();
svc.WaitForStatus(ServiceControllerStatus.Stopped, new System.TimeSpan(0, 0, 20));
svc.Start();
svc.WaitForStatus(ServiceControllerStatus.Running, new System.TimeSpan(0, 0, 20));
svc.Dispose();
}
catch (Exception ex)
{
Logging.WriteException(ex);
}
}
Main Program
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
try
{
ServiceBase[] ServicesToRun =
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
}
catch (Exception)
{
}
}
The correct way to manage restart of services is by using Windows Service Recovery Actions, described here.
They allow you to tell the Service Control Manager what to do in the event of a failure, including any restart actions, how many times to attempt a restart, and how long to wait between attempts.
This is way more robust than anything you could write in the service code itself.
Is it possible to debug the Windows services in Visual Studio?
I used code like
System.Diagnostics.Debugger.Break();
but it is giving some code error like:
I got two event error: eventID 4096
VsJITDebugger and "The service did
not respond to the start or control
request in a timely fashion."
Use the following code in service OnStart method:
System.Diagnostics.Debugger.Launch();
Choose the Visual Studio option from the pop up message.
Note: To use it in only Debug mode, a #if DEBUG compiler directive can be used, as follows. This will prevent accidental or debugging in release mode on a production server.
#if DEBUG
System.Diagnostics.Debugger.Launch();
#endif
You can also try this.
Create your Windows service and install and start…. That is, Windows services must be running in your system.
While your service is running, go to the Debug menu, click on Attach Process (or process in old Visual Studio)
Find your running service, and then make sure the Show process from all users and Show processes in all sessions is selected, if not then select it.
Click the Attach button
Click OK
Click Close
Set a break point to your desirable location and wait for execute. It will debug automatic whenever your code reaches to that point.
Remember, put your breakpoint at reachable place, if it is onStart(), then stop and start the service again
(After a lot of googling, I found this in "How to debug the Windows Services in Visual Studio".)
You should separate out all the code that will do stuff from the service project into a separate project, and then make a test application that you can run and debug normally.
The service project would be just the shell needed to implement the service part of it.
Either that as suggested by Lasse V. Karlsen, or set up a loop in your service that will wait for a debugger to attach. The simplest is
while (!Debugger.IsAttached)
{
Thread.Sleep(1000);
}
... continue with code
That way you can start the service and inside Visual Studio you choose "Attach to Process..." and attach to your service which then will resume normal exution.
Given that ServiceBase.OnStart has protected visibility, I went down the reflection route to achieve the debugging.
private static void Main(string[] args)
{
var serviceBases = new ServiceBase[] {new Service() /* ... */ };
#if DEBUG
if (Environment.UserInteractive)
{
const BindingFlags bindingFlags =
BindingFlags.Instance | BindingFlags.NonPublic;
foreach (var serviceBase in serviceBases)
{
var serviceType = serviceBase.GetType();
var methodInfo = serviceType.GetMethod("OnStart", bindingFlags);
new Thread(service => methodInfo.Invoke(service, new object[] {args})).Start(serviceBase);
}
return;
}
#endif
ServiceBase.Run(serviceBases);
}
Note that Thread is, by default, a foreground thread. returning from Main while the faux-service threads are running won't terminate the process.
A Microsoft article explains how to debug a Windows service here and what part anyone can miss if they debug it by attaching to a process.
Below is my working code. I have followed the approach suggested by Microsoft.
Add this code to program.cs:
static void Main(string[] args)
{
// 'If' block will execute when launched through Visual Studio
if (Environment.UserInteractive)
{
ServiceMonitor serviceRequest = new ServiceMonitor();
serviceRequest.TestOnStartAndOnStop(args);
}
else // This block will execute when code is compiled as a Windows application
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ServiceMonitor()
};
ServiceBase.Run(ServicesToRun);
}
}
Add this code to the ServiceMonitor class.
internal void TestOnStartAndOnStop(string[] args)
{
this.OnStart(args);
Console.ReadLine();
this.OnStop();
}
Now go to Project Properties, select tab "Application" and select Output Type as "Console Application" when debugging, or "Windows Application" when done with debugging, recompile and install your service.
You can make a console application. I use this main function:
static void Main(string[] args)
{
ImportFileService ws = new ImportFileService();
ws.OnStart(args);
while (true)
{
ConsoleKeyInfo key = System.Console.ReadKey();
if (key.Key == ConsoleKey.Escape)
break;
}
ws.OnStop();
}
My ImportFileService class is exactly the same as in my Windows service's application, except the inheritant (ServiceBase).
I found this question, but I think a clear and simple answer is missing.
I don't want to attach my debugger to a process, but I still want to be able to call the service OnStart and OnStop methods. I also want it to run as a console application so that I can log information from NLog to a console.
I found these brilliant guides that does this:
Debugging a Windows Service Project
Easier way to debug a Windows service
Start by changing the projects Output type to Console Application.
Change your Program.cs to look like this:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
// Startup as service.
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
if (Environment.UserInteractive)
{
RunInteractive(ServicesToRun);
}
else
{
ServiceBase.Run(ServicesToRun);
}
}
}
Then add the following method to allow services running in interactive mode.
static void RunInteractive(ServiceBase[] servicesToRun)
{
Console.WriteLine("Services running in interactive mode.");
Console.WriteLine();
MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart",
BindingFlags.Instance | BindingFlags.NonPublic);
foreach (ServiceBase service in servicesToRun)
{
Console.Write("Starting {0}...", service.ServiceName);
onStartMethod.Invoke(service, new object[] { new string[] { } });
Console.Write("Started");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(
"Press any key to stop the services and end the process...");
Console.ReadKey();
Console.WriteLine();
MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop",
BindingFlags.Instance | BindingFlags.NonPublic);
foreach (ServiceBase service in servicesToRun)
{
Console.Write("Stopping {0}...", service.ServiceName);
onStopMethod.Invoke(service, null);
Console.WriteLine("Stopped");
}
Console.WriteLine("All services stopped.");
// Keep the console alive for a second to allow the user to see the message.
Thread.Sleep(1000);
}
I use a great Nuget package called ServiceProcess.Helpers.
And I quote...
It helps windows services debugging by creating a play/stop/pause UI when running with a debugger attached, but also allows the service to be installed and run by the windows server environment.
All this with one line of code.
http://windowsservicehelper.codeplex.com/
Once installed and wired in all you need to do is set your windows service project as the start-up project and click start on your debugger.
You can also try System.Diagnostics.Debugger.Launch() method. It helps in taking the debugger pointer to the specified location and you can then debug you code.
Before this step please install your service.exe using the command line of Visual Studio command prompt - installutil projectservice.exe
Then start your service from the Control Panel -> Administrative Tools -> Computer Management ->Service and Application -> Services -> Your Service Name
I just added this code to my service class so I could indirectly call OnStart, similar for OnStop.
public void MyOnStart(string[] args)
{
OnStart(args);
}
I'm using the /Console parameter in the Visual Studio project Debug → Start Options → Command line arguments:
public static class Program
{
[STAThread]
public static void Main(string[] args)
{
var runMode = args.Contains(#"/Console")
? WindowsService.RunMode.Console
: WindowsService.RunMode.WindowsService;
new WinodwsService().Run(runMode);
}
}
public class WindowsService : ServiceBase
{
public enum RunMode
{
Console,
WindowsService
}
public void Run(RunMode runMode)
{
if (runMode.Equals(RunMode.Console))
{
this.StartService();
Console.WriteLine("Press <ENTER> to stop service...");
Console.ReadLine();
this.StopService();
Console.WriteLine("Press <ENTER> to exit.");
Console.ReadLine();
}
else if (runMode.Equals(RunMode.WindowsService))
{
ServiceBase.Run(new[] { this });
}
}
protected override void OnStart(string[] args)
{
StartService(args);
}
protected override void OnStop()
{
StopService();
}
/// <summary>
/// Logic to Start Service
/// Public accessibility for running as a console application in Visual Studio debugging experience
/// </summary>
public virtual void StartService(params string[] args){ ... }
/// <summary>
/// Logic to Stop Service
/// Public accessibility for running as a console application in Visual Studio debugging experience
/// </summary>
public virtual void StopService() {....}
}
Unfortunately, if you're trying to debug something at the very start of a Windows Service operation, "attaching" to the running process won't work. I tried using Debugger.Break() within the OnStart procecdure, but with a 64-bit, Visual Studio 2010 compiled application, the break command just throws an error like this:
System error 1067 has occurred.
At that point, you need to set up an "Image File Execution" option in your registry for your executable. It takes five minutes to set up, and it works very well. Here's a Microsoft article where the details are:
How to: Launch the Debugger Automatically
Try Visual Studio's very own post-build event command line.
Try to add this in post-build:
#echo off
sc query "ServiceName" > nul
if errorlevel 1060 goto install
goto stop
:delete
echo delete
sc delete "ServiceName" > nul
echo %errorlevel%
goto install
:install
echo install
sc create "ServiceName" displayname= "Service Display Name" binpath= "$(TargetPath)" start= auto > nul
echo %errorlevel%
goto start
:start
echo start
sc start "ServiceName" > nul
echo %errorlevel%
goto end
:stop
echo stop
sc stop "ServiceName" > nul
echo %errorlevel%
goto delete
:end
If the build error with a message like Error 1 The command "#echo off sc query "ServiceName" > nul so on, Ctrl + C then Ctrl + V the error message into Notepad and look at the last sentence of the message.
It could be saying exited with code x. Look for the code in some common error here and see how to resolve it.
1072 -- Marked for deletion → Close all applications that maybe using the service including services.msc and Windows event log.
1058 -- Can't be started because disabled or has no enabled associated devices → just delete it.
1060 -- Doesn't exist → just delete it.
1062 -- Has not been started → just delete it.
1053 -- Didn't respond to start or control → see event log (if logged to event log). It may be the service itself throwing an exception.
1056 -- Service is already running → stop the service, and then delete.
More on error codes here.
And if the build error with message like this,
Error 11 Could not copy "obj\x86\Debug\ServiceName.exe" to "bin\Debug\ServiceName.exe". Exceeded retry count of 10. Failed. ServiceName
Error 12 Unable to copy file "obj\x86\Debug\ServiceName.exe" to "bin\Debug\ServiceName.exe". The process cannot access the file 'bin\Debug\ServiceName.exe' because it is being used by another process. ServiceName
open cmd, and then try to kill it first with taskkill /fi "services eq ServiceName" /f
If all is well, F5 should be sufficient to debug it.
In the OnStart method, do the following.
protected override void OnStart(string[] args)
{
try
{
RequestAdditionalTime(600000);
System.Diagnostics.Debugger.Launch(); // Put breakpoint here.
.... Your code
}
catch (Exception ex)
{
.... Your exception code
}
}
Then run a command prompt as administrator and put in the following:
c:\> sc create test-xyzService binPath= <ProjectPath>\bin\debug\service.exe type= own start= demand
The above line will create test-xyzService in the service list.
To start the service, this will prompt you to attach to debut in Visual Studio or not.
c:\> sc start text-xyzService
To stop the service:
c:\> sc stop test-xyzService
To delete or uninstall:
c:\> sc delete text-xyzService
Debug a Windows Service over http (tested with VS 2015 Update 3 and .Net FW 4.6)
Firstly, you have to create a Console Project within your VS Solution(Add -> New Project -> Console Application).
Within the new project, create a class "ConsoleHost" with that code:
class ConsoleHost : IDisposable
{
public static Uri BaseAddress = new Uri(http://localhost:8161/MyService/mex);
private ServiceHost host;
public void Start(Uri baseAddress)
{
if (host != null) return;
host = new ServiceHost(typeof(MyService), baseAddress ?? BaseAddress);
//binding
var binding = new BasicHttpBinding()
{
Name = "MyService",
MessageEncoding = WSMessageEncoding.Text,
TextEncoding = Encoding.UTF8,
MaxBufferPoolSize = 2147483647,
MaxBufferSize = 2147483647,
MaxReceivedMessageSize = 2147483647
};
host.Description.Endpoints.Clear();
host.AddServiceEndpoint(typeof(IMyService), binding, baseAddress ?? BaseAddress);
// Enable metadata publishing.
var smb = new ServiceMetadataBehavior
{
HttpGetEnabled = true,
MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 },
};
host.Description.Behaviors.Add(smb);
var defaultBehaviour = host.Description.Behaviors.OfType<ServiceDebugBehavior>().FirstOrDefault();
if (defaultBehaviour != null)
{
defaultBehaviour.IncludeExceptionDetailInFaults = true;
}
host.Open();
}
public void Stop()
{
if (host == null)
return;
host.Close();
host = null;
}
public void Dispose()
{
this.Stop();
}
}
And this is the code for the Program.cs class:
public static class Program
{
[STAThread]
public static void Main(string[] args)
{
var baseAddress = new Uri(http://localhost:8161/MyService);
var host = new ConsoleHost();
host.Start(null);
Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();
host.Stop();
}
}
Configurations such as connectionstrings should be copied in the App.config file of the Console project.
To sturt up the console, righ-click on Console project and click Debug -> Start new instance.
Just add a contructor to your service class (if you don't have it already). Below, you can check and example for visual basic .net.
Public Sub New()
OnStart(Nothing)
End Sub
After, that, right-click on project and select "Debug -> Start a new instance".
I have built a Windows service, now I want it to auto-update. I have read about a creating a second service to do that or different program , cant use click one, what about myBuild? Does anyone know it? What is the best way? Can I just change assemblies?
If you want your service to run while you are performing an update, here is what I had done before to achieve this:
Put your updateble logic into a separate DLL.
Create an AppDomain within your service.
Create file monitor that fires an event whenever you copy that file (you can use MSFT Ent Lib Updates)
Unload the old dll while blocking (queue) the threads that execute stuff from that dll
Load in the new dll file into the app domain.
Let your threads know to continue processing.
Download the new exe and any additional assembly's.
Rename your existing assembly's.
Copy in your new assembly's.
Restart Service. You can build the service restart function into your main service exe.
When service starts check for renamed files from step 2 and delete them to clean up.
To restart your service do
System.Diagnostics.Process.Start
(System.Reflection.Assembly.GetEntryAssembly().Location)
Then in your service do
private const string _mutexId = "MyUniqueId";
private static Mutex _mutex;
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
try
{
bool alreadyRunning = false;
try
{
Mutex.OpenExisting(_mutexId);
alreadyRunning = true;
}
catch (WaitHandleCannotBeOpenedException)
{
alreadyRunning = false;
}
catch
{
alreadyRunning = true;
}
if (alreadyRunning)
{
using (ServiceController sc = new ServiceController("MyServiceName"))
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 120));
sc.Start();
}
return;
}
}
catch
{
}
_mutex = new Mutex(true, _mutexId);
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
// Load the service into memory.
ServiceBase.Run(ServicesToRun);
_mutex.Close();
}
You could modify your Windows Service so that it is simply a runner for your main application, and has the functionality to update your main application.
So you would have:
Service.exe: Runs Application.exe, monitors remote location for updates to Application.exe. Sends start/stop events to Application.exe
Application.exe : What used to be your Service.exe. Recieves start/stop events.