A
A
Artem Ivantsov2015-04-01 08:22:16
.NET
Artem Ivantsov, 2015-04-01 08:22:16

How to pause or kill a child thread in C#?

I have a child thread that is doing something in an infinite loop.
At some point in time, I need to:
1. Kill the child thread. Now I am doing something similar

private Thread _thread;
        private Boolean _isWorking;
        private void DoWork()
        {
            while(_isWorking)
            {
                Console.WriteLine("SomeWork");
                Thread.Sleep(1000);
            }
        }

        public void Start()
        {
            _thread = new Thread(DoWork);
            _isWorking = true;
            _thread.Start();
        }

        public void Stop()
        {
            _isWorking = false;
            while (_thread.ThreadState != ThreadState.Stopped)
                Thread.Sleep(100);
        }

I know about the Abort method, but it can leak resources. Maybe there is a smarter method without constantly checking the flag?
2. Freeze the child thread for an infinite amount of time. It is possible as an option to make one more check of the flag and if it passes, then enter the AutoResetEvent. And to wake up the thread, we reset the AutoResetEvent. There is also an option to do an endless sleep, and use Interrupt to wake up. But here again, a constant check of the flag comes out.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mayorovp, 2015-04-01
@Ramirag

To check for completion inside the thread, it is good to use ManualResetEvent, and wait on it:

private void DoWork()
        {
            do
            {
                Console.WriteLine("SomeWork");
            } while (!closeEvent.WaitOne(1000));
        }

Well, in order to wait for the thread to complete, there is a Join method

A
AxisPod, 2015-04-01
@AxisPod

Take a look at BackgroundWorker. Well, in the current example, instead of waiting for a stop, use the Thread.Join () method, the current thread will wait until your stop thread has completed.

N
Nubzilo, 2015-04-02
@Nubzilo

And here's how to stop a thread MSDN - How to: Create and Terminate Threads

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question