我有这样的课:
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() 之前完成第一个线程)。