Hi Tomaz,
I am not sure whether your problem is as complicated as it sounds.
Perhaps your problem is just that your thread won't terminate when the
application terminates. If this is the case, then you need the IsBackground
property...
Thread myThread = new Thread(...);
myThread.IsBackground = true;
myThread.Start();
Now your thread will terminate when the application terminates.
However, perhaps your problem is more complicated...
- You have a class which creates a thread
- Your application creates an instance of the class
- Your application deletes the instance
- Your application continues running
- You thread also continues running. Problem! You expect the thread to have
been stopped.
I have done some prototyping, and found that I cannot solve this problem. I
have created a finalizer for the class, which stops the thread, as follows:
class ThreadClass
{
....
volatile bool run = false;
~ThreadClass()
{
run = false;
}
void ThreadEntry()
{
run = true;
while (run)
{
Thread.Sleep(300);
}
}
}
However, I have been unable to force the finalizer to be called. I have
tried to make the instance available for collection, by setting it to null,
and then forcing garbage collection with GC.Collect(), but this hasn't
worked. The problem here is not terminating the thread, but getting the
finalizer to be called.
I suggest that you stop the thread from outside, by making a public method
on the thread class...
class ThreadClass
{
.....
void Stop()
{
run = false;
}
}
HTH,
Javaman
"Tomaz Koritnik" wrote:
I have a class that runs one of it's method in another thread. I use Thread
object to do this and inside ThreadMethod I have an infinite loop:
While (true)
{
// do something
Thread.Sleep(100);
}
The problem is that I don't know how to terminate the thread when my class
is destroyed. When closing application, destructor of my class is NOT called
so I can't stop thread there. Looks like destructor will be called AFTER the
thread has finished. Interesting and I'm stuck here because I don't know
where to put the code that stops the thread. Also, I want my class to stop
thread automatically upon destruction and I don't want to call some method
of my class from outside to stop the thread.
I can't believe that I can't solve this problem because doing it in Delphi
it's a child's play :).
regards
Tomaz