69
votes

I have created and installed a service a couple of times. Initially it was working fine, but after some changes in the service Code it start giving the error when I restart the service in Services.msc :

Error 1053: the service did not respond to the start or control request in a timely fashion

Code:

public partial class AutoSMS : ServiceBase
{
    public AutoSMS()
    {
        InitializeComponent();
        eventLog1.Clear();

        if (!System.Diagnostics.EventLog.SourceExists("MySource"))
        {
            System.Diagnostics.EventLog.CreateEventSource(
                "MySource", "MyNewLog");
        }
        eventLog1.Source = "MySource";
        eventLog1.Log = "MyNewLog";

        Timer checkForTime = new Timer(5000);
        checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
        checkForTime.Enabled = true;

    }

    protected override void OnStart(string[] args)
    {
        eventLog1.WriteEntry("In OnStart");
    }

    protected override void OnStop()
    {
        eventLog1.WriteEntry("In onStop.");
    }


    void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
    {
        string Time = "15:05:00";
        DateTime dateTime = DateTime.ParseExact(Time, "HH:mm:ss",
                                        CultureInfo.InvariantCulture);

        if (DateTime.Now == dateTime) ;
            eventLog1.WriteEntry(Time);
    }
}

Here is my main method code

static void Main()
{
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] 
    { 
        new AutoSMS() 
    };
    ServiceBase.Run(ServicesToRun);
}

I also tried the following steps :

  • Go to Start > Run > and type regedit
  • Navigate to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
  • With the control folder selected, right click in the pane on the right and - select new DWORD Value
  • Name the new DWORD: ServicesPipeTimeout
  • Right-click ServicesPipeTimeout, and then click Modify
  • Click Decimal, type '180000', and then click OK
  • Restart the computer

I used to install and uninstall it with following command :

installutil AutoSMS.exe

installutil /u AutoSMS.exe
30
What does the Windows event log say? Or does it say Error 1053? It could be a rights issue. Try running the service as Local System user.Silvermind
In the future it might be useful to use System.Diagnotstics.Debugger.Launch() in the Main() method so you can work with the debugger.user420667

30 Answers

39
votes

In my case, I was publishing service while it was in debug mode.

Solution was:

  • Changing solution to release mode
  • Uninstall old service with command InstallUtil -u WindowsServiceName.exe
  • installing service again InstallUtil -i WindowsServiceName.exe

It worked perfectly after.

28
votes

As others have pointed out, this error can have a multitude of causes. But in the hopes that this will help somebody out, I'll share what happened in our case. For us, our service had been upgraded to .NET 4.5, but the server did not have .NET 4.5 installed.

24
votes

After spending some time on the issue, trying solutions that didn't work, I run into this blog. It suggests to wrap the service initialization code in a try/catch block, like this, and adding EventLog

using System;
using System.Diagnostics;
using System.ServiceProcess;

namespace WindowsService
{
    static class Program
    {
        static void Main()
        {
            try
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new Service1() 
                };
                ServiceBase.Run(ServicesToRun);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Application", ex.ToString(), EventLogEntryType.Error);
            }
        }
    }
}

Then, uninstall the old service, redeploy the service with these modifications. Start the service and check out the Event Viewer/Application logs. You'll see what the real problem is, which is the underlying reason for the timeout.

11
votes

I encountered the same issue and was not at all sure how to resolve it. Yes this occurs because an exception is being thrown from the service, but there are a few general guidelines that you can follow to correct this:

  • Check that you have written the correct code to start the service: ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new WinsowsServiceToRun() }; ServiceBase.Run(ServicesToRun);
  • You need to ensure that there is some kind of infinite loop running in the class WinsowsServiceToRun

  • Finally, there may be some code which is not logging anything and closing the program abruptly (which was the case with me), in this case you will have to follow the old school of debugging which needed to write a line to a source (text/db/wherever). What I faced was that since the account running the service was not "Admin", the code was just falling off and not logging any exceptions in case it was trying to write to "Windows Event Log" even though the code was there to log exceptions. Admin privilege is actually not needed for logging to Even Log but it is needed to define the source. In case source of the event is not already defined in the system and the service tries to log it for the first time without admin privilege it fails. To solve this follow below steps:

    1. Open command prompt with admin privilege
    2. Paste the command : eventcreate /ID 1 /L APPLICATION /T INFORMATION /SO <<Source>> /D "<<SourceUsingWhichToWrite>>"
    3. Press enter
    4. Now start the service
10
votes

I have just tried this code locally in .Net 4.5 and the service starts and stops correctly for me. I suspect your problem may be around creating the EventLog source.

The method:

EventLog.SourceExists("MySource")

requires that the user running the code must be an administrator, as per the documentation here:

http://msdn.microsoft.com/en-us/library/x7y6sy21(v=vs.110).aspx

Check that the service is running as a user that has administrator privileges.

7
votes

It is because of the Microsoft Windows Service Control, it controls sometimes the state of the services. If the service don´t send a respond in 30 seconds, then you will have this error.

You can modified the registry, so the service will have more time to respond

Go to Start > Run > and type regedit
Navigate to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
With the control folder selected, right click in the pane on the right and select new DWORD Value
Name the new DWORD: ServicesPipeTimeout 
Right-click ServicesPipeTimeout, and then click Modify
Click Decimal, type '180000', and then click OK
Restart the computer

Or be sure that in that moment there is not another process talking with the service, maybe there is a conflict I don´t know

5
votes

After spending too much time on this issue. I found the EventLog cause all that mess although I used it properly.

Whoever tackle this issue, I would suggest you to get rid of the EventLog. Use better tools like "log4net".

4
votes

I was getting exactly same issue, All I have done is to to change the Debug mode to Release while compiling the dll. This has solved my probelm, how/why? I dont know I have already asked a question on SO

4
votes

Also, you need to check your configuration file content.

You need to check below the section.

<startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>

Coz above section need to match with yours .net framework.

4
votes

In the case I ran into this morning, the culprit was a malformed config file. The config file had an close comment tag without the open comment tag. So, double check your config files for errors.

2
votes

Check ConnectionStrings if you are using EntityFramework or any other means to initiate database connections at the service startup.

In my case when i got the error Error 1053 the service did not respond to the start or control request in a timely fashion this is what was going wrong:

I was using EntityFramework and had the connection strings wrong. So basically at startup the EntityFramework failed to connect to the database using the incorrect Connection String and timed out.

Just had to replace the database connection string with the correct one and it worked fine.

Did not need any framework update or any other system/configuration change at all.

2
votes

This worked for me. Basically make sure the Log on user is set to the right one. However it depends how the account infrastructure is set. In my example it's using AD account user credentials.

In start up menu search box search for 'Services' -In Services find the required service -right click on and select the Log On tab -Select 'This account' and enter the required content/credentials -Ok it and start the service as usual

enter image description here

2
votes

I have installed .Net 4.6 on my WindowsServer computer and the error was fixed.

Your control should be this way:

  1. Check the .net version of your WindowsService
  2. Then check the .net version of your computer
  3. Match that version, since it's probably not matched
2
votes

If you would like to register a .NET core 3.1 executable as a Windows Service, please ensure that you added the nuget package Microsoft.Extension.Hosting.WindowsServices in version 3.1.7 or above and initialize the hostBuilder like in the following example:

using Microsoft.Extensions.Hosting;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] arguments)
        {
            IHostBuilder hostBuilder = Host.CreateDefaultBuilder(arguments);
            hostBuilder.UseWindowsService();
            hostBuilder.Build().Run();
        }
    }
}

Now you are able to install the executable and start it as a windows service:

sc.exe create ConsoleApp1 binPath= "<BIN_PATH>\ConsoleApp1.exe"
1
votes

One of possible solutions for this problem [It fixed issue at my end and my application is JAVA based application ]:

1) check your application is pointing to correct java version(check the java version and path in your application).

OR

2)check the configured java version i.e check whether it is 32-bit version or 64-bit version(based on your application). if you are using 32-bit then you should use 32-bit version JSL, else JSL will cause this issue.

1
votes

This is usually caused by an uncaught exception in the service itself. (Configuration file errors eg). Opening a command prompt and starting the service executable manually wil perhaps reveal the exception been thrown.

1
votes

In my experience, I had to stop my existing service to update code. after updating the code and while START the Service I got the same error "Error 1053 the service did not respond to the start or control request in a timely fashion".

But this got resolve after RESTARTING THE MACHINE.

1
votes

I know this is old question, I used to write my own VB.NET windows service, and it has no issue to start on MS windows 7 and MS windows 10.

I have this issue when I install the windows services on latest MS windows 10 patch. The reason the windows service doesn't run it is because the .NET version that needed for the window services to run is not presented in the installed PC.

After you have installed the windows services. go to the install folder for example C:\Program files (x86)\Service1\Service1.exe and double click to run it. If there is missing .NET framework package, it will prompt the user to download it. Just download and and wait for it to install.

After that restart the windows services in services.msc. Hope this answer will help someone who face the issue. I know issue is caused by .NET framework version.

1
votes

I scratched my head to clear this error This error might be caused if you are debugging it in the code like

static void Main()
{
 #if DEBUG
            MailService service = new MailService();
             service.Ondebug();
 #else
             ServiceBase[] ServicesToRun;
             ServicesToRun = new ServiceBase[]
             {
                 new MailService()
             };
             ServiceBase.Run(ServicesToRun);
 #endif
         }
     }

After clearing the if,else and endif in the code like this the error has not appeared again....hope it helps....

static void Main()
{

    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[]
    {
        new MailService()
    };
    ServiceBase.Run(ServicesToRun);

}
0
votes

In my case, the issue was about caching configuration which is set in the App.config file. Once I removed below lines from the App.config file, the issue was resolved.

<cachingConfiguration defaultCacheManager="MyCacheManager">
<cacheManagers>
  <add name="MyCacheManager" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
       expirationPollFrequencyInSeconds="60"
       maximumElementsInCacheBeforeScavenging="50000"
       numberToRemoveWhenScavenging="1000"
       backingStoreName="NullBackingStore" />
</cacheManagers>
<backingStores>
  <add type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
       name="NullBackingStore" />
</backingStores>

0
votes

I have removed

EventLog.Exists

and fixed.

0
votes

In my case I apparently had some extra symbols in my App.config file that I did not notice when building my solution. So I recomend to check the configuration file for errors first before taking steps with changing registry keys, switching configuration modes, etc.

0
votes

I had two services running who were accidentally coupled to the same EventSource eventLog.Source = "MySource"; After uninstalling both services, and reinstalling the one that suffered from error 1053, my service started up normally.

0
votes

Check if the service starting code is correct,

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] 
{ 
    new WinsowsServiceToRun() 
};
ServiceBase.Run(ServicesToRun);

Also, remove any debug codes. ie,

  #If Debug
         ...
         ...
         ...
        #else
         ...
         ...
        #endif
0
votes

I had same problem. Unchecking "Sing the ClickOnce manifest", "Sign the assembly" and "Enable ClickOnce security settings" in project properties helped

0
votes

My issue was the one with appsettings.json not copying to release build folder during build and simple putting it into the ...\bin\Release folder and copying launchSettings.json content to appsettings.json solved the problem for me.

0
votes

I had the same issue. Seems like when starting the service the main thread shouldnt be the main worker thread. By simply creating a new thread and handing the main work to that thread solved my issue.

0
votes

this error can be caused due to various reasons. to identify the reason add try/ catch when service is run.

        try
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new Service1() 
                };
                <span class="skimlinks-unlinked">ServiceBase.Run(ServicesToRun</span>);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Application", ex.ToString(), <span class="skimlinks-unlinked">EventLogEntryType.Error</span>);
            }
0
votes

As nobody has mentioned I will add it (even if it is a stupid mistake). In case you are on Windows 10 you don't usually need to restart, but

-> Make sure to CLOSE any open properties pages of the "services"-window in case you have just installed the service (and still have opened the properties page of the old service).

I'm talking about this window:

Services list

After closing all services windows and re-trying -> it worked. In contrast to the OP I got Error 1053 basically immediately (without windows waiting on anything)

0
votes