question

qycxqycx-8916 avatar image
0 Votes"
qycxqycx-8916 asked JarvanZhang-MSFT commented

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

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

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered JarvanZhang-MSFT commented

Hello @qycxqycx-8916 ,​

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.


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi, @qycxqycx-8916
May I know if you have got any chance to check my answer? I am glad to help if you have any other questions.

0 Votes 0 ·