Share via

how to write xamarin code without memory ( activity ) leak?

qycx qycx 1 Reputation point
2021-07-16T07:10:37.423+00:00

I use xamarin to write a very simple app. to start a very simple activity. but, when I use leakCanady, it reports a leak. the mainActivity is as follows.

namespace SampleApp { [Activity(Label = "SampleApp", MainLauncher = true)] public class MainActivity : Activity { private Button _button;

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.main);
    _button = FindViewById<Button>(Resource.Id.button);
    _button.Click += OnButtonClicked;
}

protected override void OnDestroy()
{
    _button.Click -= OnButtonClicked;
    _button.Dispose();
    base.OnDestroy();
    Dispose();
}

private void OnButtonClicked(object sender, EventArgs e)
{
    StartActivity(typeof(LeakingActivity));

}
}

and the new activity is as follows public class LeakingActivity : AppCompatActivity { //private TextView _textView;

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.layout1);
    //_textView = FindViewById<TextView>(Resource.Id.textView);
}



protected override void OnDestroy()
{
    // Dispose all disposable members
    //_textView.Dispose();

    base.OnDestroy();

}

}
}

Please help me to solve it. thanks

Developer technologies | .NET | Xamarin
0 comments No comments

1 answer

Sort by: Most helpful
  1. JarvanZhang 23,971 Reputation points
    2021-07-19T06:57:44.683+00:00

    Hello @qycx qycx ,​

    Welcome to our Microsoft Q&A platform!

    but, when I use leakCanady, it reports a leak

    It seems that you didn't add the Dispose command for the 'LeakingActivity' in OnDestroy method. Please add it and test.

       protected override void OnDestroy()  
        {  
            // Dispose all disposable members  
            //_textView.Dispose();  
            base.OnDestroy();  
         
            Dispose();  
        }  
    

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.