Since Thread.Abort is so bad, the normal alternative is to do:
volatile bool runBackgroundThread;
then
while(runBackgroundThread) {…}
In my code, there is a start and stop function which would set runBackgroundThread to different values, then create a new thread in the start function.
I was worried about the scenario where the user stops and starts really quickly, which would mean that I would have to wait until the 1st thread dies before starting the 2nd. Then I have to consider what happens if the background thread takes too long on it’s last iteration, and then use some sort of blocking. Otherwise it’s possible to have 2 background threads running… one being a zombie thread.
So what I did was:
public static void Heartbeat()
{
Thread currentThread = heartbeatThread;
while (currentThread == heartbeatThread)
{ … }
}
Where heartbeatThread is defined in the class. I think this should work fine except for the odd case when the new thread is assigned to the same pointer as the old thread. Is that possible?
I think I have to think about this more.
edit: I think a better way is to actually pass the thread pointer in to the function which will run in the thread instead. This avoids the possiblity of the thread being assigned to between initialization and the thread running and acquiring the pointer to its own thread.
example:
backgroundThread = new Thread(Heartbeat);
backgroundThread .IsBackground = true;
backgroundThread .Start(backgroundThread );
…
public static void Heartbeat(Object currentThread)
{
while ((Thread)currentThread == heartbeatThread)
{ … }
}
edit 2: use Thread.GetHashCode() instead