C# 为什么';收集次线程中使用的t对象
我有一门课是这样的:C# 为什么';收集次线程中使用的t对象,c#,multithreading,xamarin.ios,garbage-collection,destructor,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 DoJobAs
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
编辑:
这也没有帮助(需要超时以确保在调用GC.Collect()之前完成第一个线程)。以下程序在我的系统(不是MONO)上按预期工作 当你尝试时会发生什么?如果它不起作用,那么在你正在使用的Mono的实现中它看起来有点奇怪-这不是一个很好的答案,但至少你知道它应该起作用
您希望GC什么时候运行?您不希望它在
base.ViewDidLoad()
返回之前运行,是吗?实例是否看到过作用域的结尾?确实看到了。更正了帖子。如果显式调用GC会发生什么?什么都不会发生)它仍然不会被收集。好吧,你的代码在Mono的控制台应用程序中不起作用,至少在Mac=(这就是为什么我担心这是Mono的问题,而不是我的问题。最后它与“发布”版本一起工作。在“调试”中不起作用模式。问题在于调试器启动时没有按预期调试程序。jitter和GC知道调试器已连接,使GC的攻击性降低。因为调试程序真的很奇怪,而您的值突然开始消失,因为GC决定它可以清理程序无法处理的内容罗格伦不再使用了。
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();
}
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();
}
}
}