Using a Cross Thread Boolean to Abort Thread
Lets say we have this code:
bool KeepGoing = true;
DataInThread = new Thread(new ThreadStart(DataInThreadMethod));
DataInThread.Start();
//bla bla time goes on
KeepGoing = false;
private void DataInThreadMethod()
{
while (KeepGoing)
{
//Do stuff
}
}
}
Now the idea is that using the boolean is a safe way to terminate the thread however because that boolean exists o开发者_JAVA百科n the calling thread does that cause any issue?
That boolean is only used on the calling thread to stop the thread so its not like its being used elsewhere
You need to clarify exactly what / where KeepGoing
is, but no; it is not safe. It can be held in a register on x86 (but this is unlikely in most non-trivial examples). You need to make it volatile
, or to synchronize (lock
etc) access to it. For an example, see here.
Hopefully I'm not going off on a tangent with this answer, but:
Jon's Worker class example has an alternative to what you're doing, which is thread safe. Two problem I've found with the while(boolVariable)
approach is some tasks take longer than others (assuming you're performing more than one task) which means the stop isn't caught until the end of that task. The other is what happens when you get to the end of the loop? Break perhaps, or just repeat that task forever, which isn't always what you want if, for example, you're downloading a list of files.
精彩评论