WHy does Windows Service restart?

Coreysan 1,736 Reputation points
2024-10-01T02:59:35.41+00:00

I have a windows service in C# that updates a database. One particular method occasionally takes longer by 2-3 minutes, so it throws an error mentioning timeout. But then the entire program restarts.

If any other method times out, it will also restart. (I use a custom log to report success or failure of each method.)

I have tested with RequestAdditionalTime, and it doesn't help. The program still restarts. If I start a new thread, it restarts.

IS there a way to code the program to simply report errors and move on, and I"ll worry about the

problem(s)?

My approach was to write a class to run several methods in sequential order, just like a SQL Agent job runs steps.

If a method fails, I get out of the class and end. But I don't understand why the service starts again?

WHat principles can I keep in mind when coding this thing to end without restarting?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,905 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 46,296 Reputation points Microsoft Vendor
    2024-10-01T07:00:31.55+00:00

    Hi @Coreysan , Welcome to Microsoft Q&A,

    Updated:

    The solution for it was to increase the SqlCommand timeout to about 3 minutes.


    By default, Windows Service Manager will try to restart a service if it detects a crash. You can check the service's recovery options to make sure it's not restarting when the service fails.

    In the "Recovery" tab, look at the settings for "First Failure", "Second Failure", and "Subsequent Failures". You can set them to "No Action" to prevent the service from automatically restarting.

    If you start a new thread to handle a task, make sure that thread is not interrupted by a change in the service's state. You can consider using an asynchronous task or BackgroundWorker to handle these long-running operations.

    Task.Run(() =>
    {
    try
    {
    // Execute your task
    }
    catch (Exception ex)
    {
    // Log an error
    LogError(ex);
    }
    });
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Coreysan 1,736 Reputation points
    2024-10-07T04:11:43.8866667+00:00

    Jiale, the solution for me was to increase the SqlCommand timeout to about 3 minutes. That did the trick!

    I appreciate your input because it helped me explore more deeply, so again, thank you so very much!


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.