views:

400

answers:

3

A parent has several child threads.

If user click on stop button the parent thread should be killed with all child threads.

//calls a main thread           
 mainThread = new Thread(new ThreadStart(startWorking));
 mainThread.Start(); 
////////////////////////////////////////////////
   startWorking()
{
    ManualResetEventInstance                    =   new ManualResetEvent(false);
    ThreadPool.SetMaxThreads(m_ThreadPoolLimit, m_ThreadPoolLimit);

    for(int i = 0; i < list.count ; i++)
   {        

        ThreadData obj_ThreadData   =   new ThreadData();
        obj_ThreadData.name      =   list[i];

        m_ThreadCount++;             

        //execute 
        WaitCallback obj_waitCallBack = new WaitCallback(startParsing);

        ThreadPool.QueueUserWorkItem(obj_waitCallBack, obj_ThreadData);
    }
  ManualResetEventInstance.WaitOne();
}

I want to kill mainThread.

+9  A: 

General advice: don't kill threads (see e.g. Killing a thread). There are all sorts of nasty resource leaks and data corruption risks involved.

Make the threads well behaved instead, and make them finish their work when signalled instead, through whatever IPC mechanism you prefer.

I don't recall the .NET API's recognizing parent and child threads. That would make the relationship your responsibility to track.

Pontus Gagge
+2  A: 

You definitely do not want to kill any threads here, since (among other reasons) the "child threads" in question are all from the thread pool.

See this article on how to create and terminate threads.

In your case, you have multiple threads all working the startParsing method. Assuming this method has a loop in it, you would create a class-level bool called _stillWorking or something, and set it to true at the beginning of the startWorking method.

Inside the loop in startParsing, you check that _stillWorking is true each time through. To "cancel" all these threads, then, you just set _stillWorking to false and wait for the threads to finish.

MusiGenesis
+2  A: 

You might consider communicating the request to quit from the child thread back to the parent and then dealing with it there. I think you'll find it much simpler overall.

Jay