作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这样一个类:
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/
我是一名优秀的程序员,十分优秀!