Monodroid GREF problem best practice?

前端 未结 3 1683
醉话见心
醉话见心 2021-01-27 03:51

I have the following test code (based on standard monodroid HelloWorld)

namespace TestGREF
{
    [Activity (Label = \"TestGREF\", MainLauncher = true)]
    publi         


        
相关标签:
3条回答
  • 2021-01-27 04:12

    You need to release all unmanaged objects when they no longer needed. All classes that inherits from Android.Runtime.IJavaObject also inherits IDisposable so you need to dispose them.

    Here is part from my project

    private Spinner _spType;
    private ArrayAdapter _arrayAdapter;
    
    protected override void OnCreate(Android.OS.Bundle savedInstanceState)
    {
      base.OnCreate(savedInstanceState);
      _spType = FindViewById<Spinner>(Resource.Id.spinnerType);
      _arrayAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, new[] {"1","2","3","4","5"});
      _spType.Adapter = _arrayAdapter;
    }
    
    public override void Finish()
    {
        if (_spType != null)
            _spType.Dispose();
        if (_arrayAdapter != null)
            _arrayAdapter.Dispose();
        base.Finish();
    }
    
    0 讨论(0)
  • 2021-01-27 04:13

    Here is article about GC and memory management in monodroid. It can be helpful for you http://docs.xamarin.com/android/advanced_topics/garbage_collection

    0 讨论(0)
  • 2021-01-27 04:14
    for(int i=0;i<10000;i++){
        var obj = new Java.Lang.Object(new System.IntPtr(i));
    
        //...some stuff here. Instead of Java.Lang.Object may be
        //something much more useful.
    
        obj.Dispose(); //Deletes an object and GREF too. 
        //Cannot be used if object is still used in dalvik VM
    }
    

    If you cannot use Dispose() (for example, unmanaged object is a part of layout, which will be used by android lated, but not by C# code), use GC.Collect() wisely. GC.Collect() kills all the GREFs to variables, which are out of usage by Mono Environment and out of current scope.

    0 讨论(0)
提交回复
热议问题