Take the 2-minute tour ×

I have a webservice which when invoked spawns a child thread. The child thread itself has a control loop and should run until it is told to terminate at some point in the future.

I am using the following code:

namespace MyService
    public class MyService : IMyService
        // Starts a new worker loop on a new thread
        public bool startMyProcess(string Name, Guid ID)
                    // Get DB connection
                    string dbConn = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
                    TManagement tManagement = new TManagement(dbConn);

                    // If a valid ID has been entered, create a new thread
                    if (tManagement.validateID(ID) == 0)
                        MainLoop myWorker = new MainLoop();
                        Thread bw = new Thread(() => myWorker.startWebServiceLoop(Name, ID));
                        return true;
                        return false; // The ID is invalid
                    // An error has occurred
                    return false;

However, after a few successful loops (doing the same thing) the thread "bw" terminates.

I would like this child thread to continue indefinitely. I suspect that the child spawned thread is being killed once the webservice thread terminates. Is there a way to avoid this?

share|improve this question
A wild uneducated guess: does setting thread's IsBackground to false help? –  Dan Abramov Dec 21 '12 at 21:45
That's a little confusing: if the service thread terminates, then your thread should terminate too. Why would you want your thread to continue after the service thread has exited? Regardless, we don't know what's in the control loop of your thread, so it's difficult to say why your thread is exiting (i.e. it could be that your control loop has a condition which causes the thread to exit). –  Lirik Dec 21 '12 at 21:46
@DanAbramov if the OP wants the thread to continue running even after the service thread terminates, then IsBackground should be false. –  Lirik Dec 21 '12 at 21:47
I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". –  John Saunders Dec 21 '12 at 21:51

1 Answer 1

up vote 1 down vote accepted

A better design would be to use a Windows Service to host the long-running thread. Your web service could communicate to the Windows Service through a small WCF service hosted by the Windows Service.

Threads in the Windows Service can last as long as they need to last. A web service is designed for a request/response paradigm, and it doesn't surprise me to hear that it doesn't always keep track of things that hare not directly due to a request from a client.

share|improve this answer

Your Answer


