Forum guidelines
AuthorQuestion
Thread Pool with windows service
Posted By carl_sargunar on 14 Aug 2008
Hi

I was wondering the best way to implement a multi threaded windows service, to be used in similar fashion to the windows task scheduler service with added functionality.

Does anybody know of any resources or can anybody point me inthe right direction. I so far plan to have a main thread running as part of a threadpool, and each time I need to start a new task, start a new thread and add it to the thread pool. I assume then the task has finished, the thread will automatically stop and be removed from the threadpool.

Stopping the service will stop any subsequent threads from starting, using simple bool flags, but not stop any threads already running from finishing

Pseudocode would be something like this

Thread main = new thread()
Bool running;

OnStart()
{
running = true;
main.threadstart = MainThreadWorker;
main.start;
}

OnStop() { running = false; }

MainThreadWorker()
{
while (running)
{
If (new task)
  {
  Start New thread;
  Add new thread to Threadpool;
  }

  if (running) {mainthread.sleep (Some interval)}
}
Somehow kill the threadpool here;
}


thanks for your help

AuthorReply
Re: Thread Pool with windows service
Posted By Alexey Kovaltchuk on 22 Aug 2009  
hello!
there's no way to kill "ThreadPool", you can't abort it!
and there is more porblems in Managed Windows Services:
when the service starts in "OnStart" you launching the service worker thread.
in the worker thread you may use the "ThreadPool.QueueUserWorkItem(...)".
but there is one issue:
when you trying to stop your service (for example via "services.msc") while some task are running in the
"ThreadPool", your service will never accept the stop event, and the "OnStop" will never be called until
"ThreadPool" finishes all it's tasks. so the state of service will be "StopPending".
because all tasks of "ThreadPool" cannot be canceled, "ThreadPool" is not the best choise when writing
Windows Service.

Nya

SPONSORED BY

Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.