C# Thread object lifetime

后端 未结 4 688
终归单人心
终归单人心 2020-12-01 12:46

Suppose I have a code as follows:

int Main()
{
    if (true)
    {
       new Thread(()=>
          {
              doSomeLengthyOperation();
          })         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 13:02

    Word "thread" could mean several things here:

    • System.Threading.Thread object (created by new Thread()),
    • CLR thread (managed thread),
    • OS thread (un-managed thread).

    Thread object will be candidate for GC as soon as Start() method completes, because there are no more references to it.

    Managed thread will stay alive while doSomeLengthyOperation() runs.

    Quoting the article by James Kovacs, Microsoft MVP:

    A managed thread's lifetime is independent of the Thread object that creates it, a very good thing given that you wouldn't want the GC to terminate a thread that was still doing work simply because you lost all references to the associated Thread object. So the GC is collecting the Thread object, but not the actual managed thread.

    The article also contains some helpful code samples if you want to experiment yourself.

    Operating system thread, theoretically, has no one-to-one relationship with managed threads. From MSDN:

    ...a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

    In practice, however, CLR thread maps directly to a Windows thread today.

提交回复
热议问题