Imran Rizvi Imran Rizvi - 8 months ago 66
C# Question

what is the maximum time windows service wait to process stop request and how to request for additional time

I have written a windows service in c# that process a lot data. when we stop it try for sometime 20/30 seconds and then throws exception.

I want to implement ServiceBase.RequestAdditionalTime() in OnStop event.

I want to know the exact timeout after which windows service throws the exception, so that I can request additional time just before it.

I searched but did not find this default stop timeout value.


I wrote the following code to achieve it.

protected override void OnStop()
  int timeout = 10000;
  var task = Task.Factory.StartNew(() => MyTask());
  while (!task.Wait(timeout))

The above code starts a Task in Parallel to the main thread (Task start running immediately), next line is to check if task is completed or not every 10 seconds and if it is not completed it requests additional 10 seconds and keep checking till task get completed.