【发布时间】:2012-07-27 02:01:58
【问题描述】:
我有一个带有 4 个选项卡 (TabActivity) 的应用程序。由于某些原因,每次用户切换选项卡(覆盖 OnPause Activity 的方法)时,我都会调用 GC.Collect。有时(大约 1 次来自 50-100 次调用,但有时会在应用程序刚启动时发生)我的应用程序此时会挂起。
这是我的部分代码:
protected override void OnPause(){
base.OnPause();
try{
Android.Util.Log.Info("----","GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);");
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
Android.Util.Log.Info("----","GC.Collect Finished");
}catch(Exception exc){
Android.Util.Log.Info("exc.Message",exc.Message);
Android.Util.Log.Info("exc.StackTrace",exc.StackTrace);
throw exc;
}
}
这里是对应的Android日志输出
//Previous GC.Collect call, it's all ok
I/---- ( 7796): GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
D/dalvikvm( 7796): GetMethodID: method not found: Landroid/widget/EditText;.monodroidAddReference:(Ljava/lang/Object;)V
D/dalvikvm( 7796): GC_EXPLICIT freed 962 objects / 42472 bytes in 112ms
I/---- ( 7796): GC.Collect Finished
//On another call fails
I/---- ( 7796): GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
I/mono ( 7796): Stacktrace:
I/mono ( 7796):
I/mono ( 7796): at System.GC.Collect (int) <0x0001f>
I/mono ( 7796): at System.GC.Collect (int,System.GCCollectionMode) <0x00017>
I/mono ( 7796): at PixelsAndroid.CustomActivity.OnPause () <0x00067>
I/mono ( 7796): at Android.App.Activity.n_OnPause (intptr,intptr) <0x00037>
I/mono ( 7796): at (wrapper dynamic-method) object.908cefd4-40eb-4dd1-97cd-f731b2ada74a (intptr,intptr) <0x0002b>
I/mono ( 7796): at (wrapper native-to-managed) object.908cefd4-40eb-4dd1-97cd-f731b2ada74a (intptr,intptr) <0xffffffff>
没有任何异常被抛出,没有任何明显的失败原因。应用程序只是挂起,几秒钟后我收到 Android 操作系统警报:“Oppps,您的应用程序卡住了。强制关闭或等待?”
有人遇到过吗?
【问题讨论】:
-
你为什么首先调用 GC.Collect() ?为此,我从来没有正当理由在 MonoDroid 或 Windows 上强制执行 GC。当我看到 GC.Collect() 时,这是一种需要重新思考的代码异味。
-
我把它当作this problem的特殊解决方案使用
-
减少您加载的实例数量。坦率地说:如果您的代码加载了太多列表项,以至于您达到了 GREF 限制(即您没有对数据进行分页),那么您需要重新设计您的解决方案。请记住,这是一个移动设备,而不是您的笔记本电脑/台式机/其他任何东西。
标签: android mono xamarin.android