Stefan Vogel
Stefan Vogel

Reputation: 25

Constructor of thread class getting called by mistake

I have a ThreadClass initaled like this

ThreadClass t = new ThreadClass();
Thread thread = new Thread(new ThreadStart(t.Run));
thread.Start();

My ThreadClass has a destructor:

~ThreadClass(){ // some stuff }

This destructor is getting called "by mistake". This means the thread is still running and is working correctly. But the destructor is called in a unpredictable manner. It's not really reproducable, but if I set a breakpoint and run my code for long time, suddenly the destructor is getting called. Is there a garbage collection cleaning up my ThreadClass. But if so, why is my Thread continue running?

Upvotes: 0

Views: 30

Answers (1)

SLaks
SLaks

Reputation: 887453

The GC will collect an object some time after the last reference goes out of scope.

If your Run() method doesn't use this, your instance can be collected at any time. GC.KeepAlive() can change this behavior; read its documentation carefully.

This is why you should not use finalizers for anything other than cleaning up native resources.

Upvotes: 1

Related Questions