简体   繁体   中英

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

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 .

I'd recommend having a System.Timers.Timer , in which Elapsed event you'd do the work of logging. In OnStart you simply start the timer, while OnStop you clean up ( Stop and Dispose the timer).

About Delay vs Sleep considerations. Easy way to remember difference is to notice, that Delay reutns a Task , so it will be run asynchronously (so execution won't be stopped ) if not await ed. Thread.Sleep on contrary, blocks current thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM