为什么二级线程中使用的't对象不被收集?

本文关键字:对象 二级 线程 为什么 | 更新日期: 2023-09-27 18:01:58

我有一个这样的类:

public class SecondaryThreadClass
{
    private string str;
    public SecondaryThreadClass ()
    {
    }
    ~SecondaryThreadClass(){
        Console.WriteLine("Secondary class's instance was destroyed");
    }
    public void DoJobAsync(){
        new Thread(() => {
//      this.str = "Hello world";
//      Console.WriteLine(this.str);
            Console.WriteLine("Hello world");
        }).Start();
    }
}

当我取消这两行注释并注释Console时。WriteLine("Hello world");相反,我的析构函数永远不会被调用。因此,如果我在二级线程方法中使用"this",我的对象似乎不会被收集。呼叫者的代码在这里:

    public override void ViewDidLoad ()
    {
        SecondaryThreadClass instance = new SecondaryThreadClass();
        instance.DoJobAsync();
        base.ViewDidLoad ();
    }

如何让GC收集这些对象?如果它重要的话,我正在使用MonoTouch。

编辑:

    public void DoJobAsync(){
        new Thread(() => {
            this.str = "Hello world";
            Console.WriteLine(this.str);
    //      Console.WriteLine("Hello world");
            new Thread(() => {
                Thread.Sleep(2000);
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }).Start();
        }).Start();
    }

这也没有帮助(需要超时来确保第一个线程在GC.Collect()被调用之前完成)。

为什么二级线程中使用的't对象不被收集?

下面的程序在我的系统(不是MONO)上正常工作。

当你尝试时会发生什么?如果它不工作,那么它看起来就像你正在使用的Mono实现中的一些奇怪的东西-这不是一个答案,但至少你知道它应该工作…

using System;
using System.Threading;
namespace Demo
{
    class Program
    {
        private static void Main(string[] args)
        {
            SecondaryThreadClass instance = new SecondaryThreadClass();
            instance.DoJobAsync();
            Console.WriteLine("Press a key to GC.Collect()");
            Console.ReadKey();
            instance = null;
            GC.Collect();
            Console.WriteLine("Press a key to exit.");
            Console.ReadKey();
        }
    }
    public class SecondaryThreadClass
    {
        private string str;
        public SecondaryThreadClass()
        {
        }
        ~SecondaryThreadClass()
        {
            Console.WriteLine("Secondary class's instance was destroyed");
        }
        public void DoJobAsync()
        {
            new Thread(() =>
            {
                this.str = "Hello world";
                Console.WriteLine(this.str);
            }).Start();
        }
    }
}

您期望GC何时运行?你不会期望它在base.ViewDidLoad()返回之前运行吧?