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

We had an issue arise lately where one of our servers got rebooted and the windows services on that box did not restart after the reboot like they should.  In the event logs, we were getting the following error.

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

So after doing some research, it looked like we were doing too much in the Main() method and/or the constructor. In other words, all our processing was not finishing prior to timing out.  Now, we can start the services just fine after the box has booted.  So the issue is most likely while the box is being booted, its resources are too thin that even with the service set to Automatic (Delayed Start) that it’s just not finishing what it needs too.

So I dove into windows services a bit to figure out where we could move the bulk of our processing for initialization.  I came up with two solutions. First I recreated the problem so that I knew that’s what the real problem is. Take a look at the following.

using System.ServiceProcess;
using System.Threading;

namespace AdamsService
{
    public partial class Service1 : ServiceBase
    {
        //Called By Main Method.
        public Service1()
        {
            InitializeComponent();
        }

        //Runs First
        private static void Main()
        {
            ServiceBase[] ServicesToRun = new ServiceBase[] { new Service1() };

            Thread.Sleep(31000); //Simulates processing time leading to a time out.

            Run(ServicesToRun);
        }

        //Runs after main
        protected override void OnStart(string[] args)
        {
        }

        protected override void OnStop()
        {
        }
    }
}

This first example shows that the majority of the processing is happening in the Main() method.  As well, if you were to move the Thread.Sleep(31000) to the constructor Service1() you will get the same results.  If you build, deploy, and try to start this service locally you will receive a message like follows when you try to start the service.

Error 1053 Windows Service Fails To Start In Timely Fashion

Error 1053 Windows Service Fails To Start In Timely Fashion

So how do we fix it?  Let’s take a look at two solutions that seem to handle the extra processing time.  The first one, I basically moved the processing to the OnStart method.  This is run through the call in the Main method Run(ServicesToRun).  Moving the processing to OnStart allowed me to successfully start and run the service.

using System.ServiceProcess;
using System.Threading;

namespace AdamsService
{
    public partial class Service1 : ServiceBase
    {
        //Called By Main Method.
        public Service1()
        {
            InitializeComponent();
        }

        //Runs First
        private static void Main()
        {
            ServiceBase[] ServicesToRun = new ServiceBase[] { new Service1() };

            Run(ServicesToRun);
        }

        //Runs after main
        protected override void OnStart(string[] args)
        {
            Thread.Sleep(31000); //Simulates processing time leading to a time out.
        }

        protected override void OnStop()
        {
        }
    }
}

The second solution that seemed to work and seemed to be a common solution among others is to spin off a new thread from the Main() method.  This allows for almost instantaneously starting of the service and then the processing continues in the background.  Take a look at the following.

using System.ServiceProcess;
using System.Threading;

namespace AdamsService
{
    public partial class Service1 : ServiceBase
    {
        //Called By Main Method.
        public Service1()
        {
            InitializeComponent();
        }

        //Runs First
        private static void Main()
        {
            ServiceBase[] ServicesToRun = new ServiceBase[] { new Service1() };

            Thread worker = new Thread(DoProcessing);
            worker.IsBackground = false;
            worker.Start();

            Run(ServicesToRun);
        }

        private static void DoProcessing()
        {
            Thread.Sleep(31000);
        }

        //Runs after main
        protected override void OnStart(string[] args)
        {
        }

        protected override void OnStop()
        {
        }
    }
}

Both seem to work equally as well from the testing that I did.  I would be interested in others opinion if you have run into similar issues.


Rounding using Math Ceiling to 5 and 0 in CSharp

Rounding has always been a bit of a struggle.  Recently I had a requirement to do some rounding for a rating type of system (i.e. x / 5 stars).  As it has been long know, the Math.Round method handles .5 a bit differently than we would like.  So let’s take a look at the specific requirements and dig into this example a bit deeper.

If greater than .0 and less than or equal to .5, display half a star

If greater than .5 and less than or equal to .0 display whole star

This made for a little bit of a trickier approach since we are want a value such as 1.1 to round to 1.5 and then wanting 1.7 to round to 2.0.  When you start breaking it apart it’s not too bad.  We are going to take advantage of the Math.Ceiling method.  Math.Ceiling returns the smallest integral value that is greater than or equal to the specified double-precision floating-point number.  In a real basic sense it’s going to round the number up.  So in our context of ratings, the following ratings of say 1.2, 1.7, and 1.9 all will round up to 2.  How does this help us?  Let’s take a look at the line doing our rounding.

double roundedRating = (Math.Ceiling(2 * currentRating)) / 2;

I think the easiest way to understand is to plug in some numbers. Lets run an example.  So per our requirements, we would expect 1.1 to give us a final rounded rating of 1.5.

double roundedRating = (Math.Ceiling(2 * 1.1)) / 2;
double roundedRating = (Math.Ceiling(2.2)) / 2;
double roundedRating = (3) / 2;
double roundedRating = 1.5;

Following through the logic above, by doubling our initial rating, we are allowing ourselves to round to a whole number, and then divide that in half to achieve our .5 rating system that is required.  Overall, not entirely complicated but turned out to be a helpful little method to round to either .5 or .0 depending on the initial rating.


For Loop UInt64 MaxValue Parallel Iteration Calculation Time

For Loop UInt64 MaxValue Parallel Iteration Calculation Time was an interesting Friday 30 Second question; if you were to iterate through a loop and you could parallelize your loop over 100 cores and each iteration took 1 nanosecond (i.e. 1 billion iterations per second) then how long would it take you to iterate over all the digits that could fit inside an UInt64?

e.g.

for (UInt64 i = 0; i < UInt64.MaxValue; i++)
{    
    ; // This operation takes 1 nanosecond and loop has no overhead
}

So this is really just a math situation. First we need to define what the value of Uint64.MaxValue is.  If we look up its value on MSDN, we know that it is a constant value of 18,446,744,073,709,551,615; that is, hexadecimal 0xFFFFFFFFFFFFFFFF.  Now at this point, it becomes common math.

This is the breakdown of how many operations will be happening per second in total across all cores.


Operations / Second / Thread = 1,000,000,000

Threads = 100

Operations / Second = 1,000,000,000 * 100 = 100,000,000,000

Now let’s apply it to the UInt64.MaxValue.

Seconds / Operation = 1 / 100,000,000,000

Total Seconds = Operations * (Seconds / Operation) = 18446744073709551615 * (1 / 100,000,000,000) = ~184467441

Minutes = 184467441/ 60 = 3074457

Hours = 3074457 / 60 = 51241

Days = 51241 / 24 = 2135

Weeks = 2135 / 7 = 305

Years = 305 / 52 = 5.86

The discussion and point that came out of this is a feature that was introduced in .Net 4.  It’s the concept of parallelizing your loops across all available processors with the Parallel.For<> loop. This will have its obvious benefits of being able to process at n times the amount of processors that are available.


Why does YUI Minify fail on char and browsers do not in JavaScript

This weeks 30 second question. Why does YUI Minify fail on char and browsers do not in JavaScript?

In JavaScript the following line of code works on all browsers that I have seen:

var char = 15;

However, the YUI minifier chokes on this line of code. Why is this? And should that line not work on browsers? i.e. why are browsers allowing that line to work?

Let’s start out with Reserved words in Javascript.  These words are words that you cannot use as variable or function names as they hold special meanings and instruction to the language.  If you haven’t guess by now, ‘char’ is a reserved keyword in JavaScript.  So in the above example we are trying to use a keyword as a variable name which causes the YUI Minify to throw a fit.  To give you an example, open up this link and plug in the following and click compress.

http://www.refresh-sf.com/yui/

var char = 15

You will be prompted with the error below.

[ERROR] 1:10:missing variable name

[ERROR] 1:0:Compilation produced 1 syntax errors.

org.mozilla.javascript.EvaluatorException: Compilation produced 1 syntax errors.
	at com.yahoo.platform.yui.compressor.YUICompressor$1.runtimeError(YUICompressor.java:154)
	at org.mozilla.javascript.Parser.parse(Parser.java:392)
	at org.mozilla.javascript.Parser.parse(Parser.java:337)
	at com.yahoo.platform.yui.compressor.JavaScriptCompressor.parse(JavaScriptCompressor.java:312)
	at com.yahoo.platform.yui.compressor.JavaScriptCompressor.<init>(JavaScriptCompressor.java:533)
	at com.yahoo.platform.yui.compressor.YUICompressor.main(YUICompressor.java:131)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:585)
	at com.yahoo.platform.yui.compressor.Bootstrap.main(Bootstrap.java:21)

That answers the first part of the question, now onto the second part of the question.  Why do browsers still allow this code snippet to work?  Well, the keyword char is not actually used by the JavaScript language.  So yes it’s labeled as a reserved keyword, but it is never been used as one. Browsers run their own compilers for JavaScript and tend to have more of a lenient stance on this subject.  They want to allow as much of the JavaScript execute as they possibly can.  So since there is not a repercussion of using this keyword, the browsers don’t take it into account as an issue.  The YUI Minify is a more standards compliant engine that will follow standards, hence why it blows up when you try to use a keyword it recognizes as a word that’s off limits.


Postfix increment and decrement operators in CSharp

Postfix increment and decrement operators are great for doing quick addition and subtraction. Using your C# knowledge and not your compiler, what will the output be?

int i = 1;
string result = String.Format("{0},{1},{2}", i--, i++, i++);
Console.WriteLine(result);

Have your guess?

The output reads as follows. 1,0,1 and the last value of i is actually 2. Why is this?  We are using post operators, meaning, the compiler is going to read the value of i, then it will increment or decrement depending.  In the above example, the last i++ happens after the value of {2} is read, so it will not be seen as 2 in the console window and is not used in any execution path.  So let’s take a look at the opposite of above.

int i = 1;
string result = String.Format("{0},{1},{2}", --i, ++i, ++i);
Console.WriteLine(result);

Have your answer for this version?

The output ends up being 0,1,2 with a final value of i =2.  The reasoning is opposite of the above.  These operators will apply the increment or decrement prior to reading i.


StackOverflow Profile