Badmiral
Badmiral

Reputation: 1589

How do you disable the timeout for a Windows Service C#?

I have a windows service that runs and starts up fine, however, it runs a background thread (multiple of them) that do some serious computation.

After a bit of digging I have found that it is due to the timeout that all windows services have. Currently, it reads from a table in a database, loads it into an object, then does some analysis on said object. This is all done in the OnStart method which then calls other methods. Is there some trick to keep the service running or any way to stop timeouts without going into the registry? Thanks

Upvotes: 3

Views: 2906

Answers (2)

Swomble
Swomble

Reputation: 909

The OnStart function is not the place for logic that takes a long time to execute. Basically you need to create a class for your logic outside of the OnStart function. You'll need to publicly declare an entry function - i.e. the one that gets the data and starts working on it.

e.g.

class ProcessingClass()
{
    public void ThreadStartProc()
    {
         GetData();
         StartProcessing();
    }
 }

In your onStart method, create a new Thread and set the ThreadStart to your ThreadStartProc function. e.g.

Thread ProcessingThread;
ProcessingClass procClass = new ProcessingClass();

protected override void OnStart(string[] args)
{
    ProcessingThread = new Thread(new ThreadStart(procClass.ThreadStartProc));
    ProcessingThread.Start();
}

protected override void OnStop()
{
     if (ProcessingThread != null)
     {
          ProcessingThread.Abort();
          ProcessingThread.Join();
          ProcessingThread = null;
     }
}

In your processing class you'll need to handle the ThreadAbortException that will get thrown when the service is stopped.

Upvotes: 5

Ralph Willgoss
Ralph Willgoss

Reputation: 12163

  1. Move your logic out of the OnStart method.
  2. Use the Service.RequestAdditionalTime() method.

See this SO answer: windows service startup timeout

Upvotes: 4

Related Questions