简体   繁体   中英

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.

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

It is not possible to restart a stopped Thread instance.

Yes. Once:

  1. The thread is stopped (eg 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM