(Xamarin,Android)此代码如何帮助减少引用实例?
(Xamarin, Android) How dose this code help Reduce Referenced Instances?
我正在 Garbage Collection -- Reduce Referenced Instances 阅读 Android 的垃圾收集文档,我不太了解这段代码的机制
class HiddenReference<T> {
static Dictionary<int, T> table = new Dictionary<int, T> ();
static int idgen = 0;
int id;
public HiddenReference ()
{
lock (table) {
id = idgen ++;
}
}
~HiddenReference ()
{
lock (table) {
table.Remove (id);
}
}
public T Value {
get { lock (table) { return table [id]; } }
set { lock (table) { table [id] = value; } }
}
}
class BetterActivity : Activity {
HiddenReference<List<string>> strings = new HiddenReference<List<string>>();
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
strings.Value = new List<string> (
Enumerable.Range (0, 10000)
.Select(v => new string ('x', v % 1000)));
}
}
HiddenReference 是如何工作的?如果 GC 会递归 扫描 BetterActivity 引用的实例,难道它不能看到 strings 字段中的列表,然后是列表中的所有字符串吗?我想我错过了什么。感谢任何帮助。
谢谢!
想法是 HiddenReference
有一个 static Dictionary<T>
。每个静态对象都被垃圾收集器视为根对象。这意味着我们有一个托管的、有根的对象。在这种情况下,GC 桥不需要检查潜在的引用,因为它可以确保该对象永远不会被收集。
注意事项:如果您在 GC 过程中发现速度变慢,则应该减少 Activity
中的引用。如果您的应用运行良好,请不要优化。
我正在 Garbage Collection -- Reduce Referenced Instances 阅读 Android 的垃圾收集文档,我不太了解这段代码的机制
class HiddenReference<T> {
static Dictionary<int, T> table = new Dictionary<int, T> ();
static int idgen = 0;
int id;
public HiddenReference ()
{
lock (table) {
id = idgen ++;
}
}
~HiddenReference ()
{
lock (table) {
table.Remove (id);
}
}
public T Value {
get { lock (table) { return table [id]; } }
set { lock (table) { table [id] = value; } }
}
}
class BetterActivity : Activity {
HiddenReference<List<string>> strings = new HiddenReference<List<string>>();
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
strings.Value = new List<string> (
Enumerable.Range (0, 10000)
.Select(v => new string ('x', v % 1000)));
}
}
HiddenReference 是如何工作的?如果 GC 会递归 扫描 BetterActivity 引用的实例,难道它不能看到 strings 字段中的列表,然后是列表中的所有字符串吗?我想我错过了什么。感谢任何帮助。
谢谢!
想法是 HiddenReference
有一个 static Dictionary<T>
。每个静态对象都被垃圾收集器视为根对象。这意味着我们有一个托管的、有根的对象。在这种情况下,GC 桥不需要检查潜在的引用,因为它可以确保该对象永远不会被收集。
注意事项:如果您在 GC 过程中发现速度变慢,则应该减少 Activity
中的引用。如果您的应用运行良好,请不要优化。