Answer the question
In order to leave comments, you need to log in
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);
}
Answer the question
In order to leave comments, you need to log in
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));
}
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question