c# - 为什么不收集辅助线程中使用的对象

标签 c# multithreading xamarin.ios garbage-collection destructor

我有这样一个类:

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() 之前完成)。

最佳答案

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

关于c# - 为什么不收集辅助线程中使用的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15199048/

相关文章:

c# - 找到 iTextSharp 对象的页码

c# tooltip backcolor 和 forecolor 不随 using 方法或其他方式改变

c# - 使用 async/await 和 System.Threading.Tasks.Parallel 时出现奇怪的执行跳转

c# - 单点触控 : send data back down the stack to another ViewController

c# - 在 C# 中重命名目录

c# - 如何在C#中继承C++/CLI接口(interface)?

java - 在主线程中等待 HTTP 请求

php - 从 PHP worker 到 Python 线程

iphone - 如何从 Web 浏览器控件中托管的 HTML 在 Safari 中打开链接?

c# - UIImageView.Image 使用 MonoTouch 发送邮件附件