C#线程对象的生命周期

C#线程对象的生命周期

问题描述:

假设我有一个代码如下:

Suppose I have a code as follows:

int Main()
{
    if (true)
    {
       new Thread(()=>
          {
              doSomeLengthyOperation();
          }).Start();
    }
    while (true)
    {
       //do nothing
    }
}

有2个线程,我会打电话给主线程正在执行的Main()函数的线程,线程被new'ed了里面的如果test作为线程A。

There are 2 threads, I'm going to call the Main thread the thread that is executing the Main() function, and the thread being new'ed up inside the "if" test as Thread A.

我的问题是,什么时候线程A被摧毁?将doSomeLenghtyOperation()能碰上完成?

My question is, when does Thread A get destroyed? Will doSomeLenghtyOperation() be able to run into completion?

由于没有引用在线程A指向,将它标记为垃圾回收的候选:

Since there are no references pointing at Thread A, will it be marked as a candidate for garbage collection:


  1. 后立即新的Thread()。开始()语句本身完成?

  2. 紧随如果(真)范围内退出后,
  3. 的doSomeLengthOperation(后)运行到完成?

  4. 从不?

我看到的例子都是抱着参考在main(),然后主线程等待退出之前,线程A加入。我很好奇上面的代码的寿命。

All the examples I see are the Main() holding the reference, and then Main thread waiting to join with thread A before exiting. I'm curious what the lifetime of the code above is.

在此先感谢!

对象会立刻进行垃圾回收,因为它是不再使用,即调用后,立即启动方法。 (它将但不会立即作为垃圾收集器在特定时间运行收集。)

The Thread object will be eligible for garbage collection as soon as it's not used any more, i.e. immediately after calling the Start method. (It will however not be collected immediately, as the garbage collector runs at specific times.)

实际的线程但不依赖于主题对象,并将继续即使对象收集运行。

The actual thread however is not relying on the Thread object, and will continue to run even if the Thread object is collected.

如果线程仍在运行时的主要方法退出时,应用程序将不会结束,直到线程完成,除非您已标记线程是一个后台线程。

If the thread is still running when the main method exits, the application will not end until the thread completes, unless you have marked the thread to be a background thread.