Search code examples
c#taskthreadpool

Windows service stuck in 'starting' state and difference between Thread.Sleep() and Task.Delay()


my windows service was stuck in starting state. Below was the code inside onstart().log() will log some value to a file.

while (true)
        {
            log();
            Thread.Sleep(TimeSpan.FromMinutes(5));
        }

after some experiments i changed onstart() to

while (true)
        {
            log();
            await Task.Delay(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
        }

once i changed the code service state changed to running and works fine. What is the difference between Thread.Sleep() and Task.Delay() i thought both are delaying execution. Can anyone help me to understand


Solution

  • The thread that calls OnStart isn't yours to do with as you will. It's actually used to respond to Service Control Manager requests directed to your service. Your service isn't considered started until you return from OnStart.

    The key difference between Thread.Sleep and Task.Delay is that the first blocks the current thread, whereas the second, (if used with await and not for a delay of 0) will end up releasing the current thread.

    Once you've added async/await to your OnStart method, you actually return from the method at the first point in execution where the code encounters an await on something that's not finished yet - your await Task.Delay.