How to force/trigger xamarin mono to GC from ADB shell?

时间:2018-07-25 05:22:13

标签: android xamarin xamarin.android mono adb

Trying this command adb shell debug.mono.profile for getting heap shot.

So what is the command to trigger GC from using adb shell?

1 个答案:

答案 0 :(得分:2)

BroadcastReceiver添加到您的应用中,该应用在GC.Collect替代中调用OnReceive

这是我使用的一个:

#if DEBUG
[BroadcastReceiver(Name = ReceiverName, Enabled = true, Exported = true)]
[IntentFilter(new string[] { IntentFilterName })]
public class MonoGCBroadcastReceiver : BroadcastReceiver
{
    const string ReceiverName = "com.sushihangover.someapp.garbagecollect";
    const string IntentFilterName = "perform.mono.gc";
    readonly string TAG = Application.Context.PackageName;

    public override void OnReceive(Context context, Intent intent)
    {
        if (intent.Action == IntentFilterName)
        {
            var generation = intent.GetIntExtra("generation", 9999);
            if (!Enum.TryParse(intent.GetStringExtra("mode"), true, out GCCollectionMode mode))
            {
                mode = GCCollectionMode.Forced;
            }
            var force = intent.GetBooleanExtra("forced", true);
            var compacting = intent.GetBooleanExtra("compacting", true);
            Log.Debug(TAG, $"GC: G:{generation} : M:{mode} : F:{force} C:{compacting}");
            GC.Collect(generation, mode, force, compacting);
        }
    }
}
#endif

现在,您可以使用adb来调用该接收者并为垃圾收集器传递可选参数。

示例:

export packageName="com.sushihangover.someapp"

adb shell setprop debug.mono.profile log:heapshot

# Start you app

adb shell am broadcast \
  -n $packageName/.garbagecollect \
  -a perform.mono.gc \
  --es mode "force" \
  --ei generation 1 \
  --ez forced true

// Clear debug.mono.profile when all done collecting your mlpd
adb shell setprop debug.mono.profile '""'