3

我有这样的课:

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() 之前完成第一个线程)。

4

1 回答 1

0

以下程序在我的系统上按预期工作(不是 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()返回之前运行是吗?

于 2013-03-04T10:29:26.040 回答