Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to kill parent thread

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.

like image 925
Royson Avatar asked Dec 13 '22 22:12

Royson


1 Answers

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.

like image 101
Pontus Gagge Avatar answered Dec 15 '22 12:12

Pontus Gagge