I am coding an application that starts and stops a thread by a command. If client receives "start" it starts the thread, and if client receives "stop" -- it stops. My concern is in thread-safety in my code and the proper practice for this problem. My code:
Thread thread = new Thread(doStuff);
...
//wait for the commands
if(command.Equals("start")
{
thread.Start();
}
if(command.Equals("stop")
{
//this code won't work of course
thread.Abort();
}
public static void doStuff()
{
while(true)
{
//do stuff
}
}
The problem is that abort will not work, because it does not know if it was even started. Also, i need to somehow know if the thread is actually alive.. Maybe I need to wrap it around abort statement and check thread.isAlive status
But what I tried to do is to create a common variable for the function.
bool running = true;
Thread thread = new Thread(doStuff);
...
//wait for the commands
if(command.Equals("start")
{
thread.Start();
}
if(command.Equals("stop")
{
//this code won't work of course
running = false;
}
public void doStuff()
{
while(running)
{
//do stuff
}
}
This implementation is horrible and causes a crash sometimes within 15 seconds. Could someone please show me an appropriate way to achieve my goal? Thank you