Svisstack
Svisstack

Reputation: 16656

new Thread() and Garbage Collection Memory Leak?

I have the following code:

new Thread(new ThreadStart(delegate()
{
    // something short
})).Start();

Can garbage collector finalize this instance of Thread while it is in the Stopped state?

Lifetime of this thread is:

  1. Before Started
  2. Running
  3. Stopped

When this Thread will end of their work this will be collected by Garbage Collector or they will keep handle to that thread for maybe restart them in future.

Upvotes: 1

Views: 1036

Answers (2)

Jon Hanna
Jon Hanna

Reputation: 113392

Yes. Once:

  1. The thread is stopped (e.g. the delegate called has returned).
  2. There isn't a rooted reference to the Thread object any more.

Then it can be collected. You won't notice though, because at this point you have no reference to the object to examine it through, there's no code running on the thread it represents, and there never will be.

I suppose you could have a WeakReference that held a reference to the object, and when its IsAlive was false you'd know it had been collected. Why would you care though?

Upvotes: 2

SLaks
SLaks

Reputation: 888293

A Thread instance are not referenced by the system after the thread terminates.

It is not possible to restart a stopped Thread instance.

Upvotes: 4

Related Questions