Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 58056

Unsubscribing from event handlers not necessary in Xamarin Forms? i.e. ok to use anonymous methods?

$
0
0

Based on some testing I have come to the conclusion that unsubscribing from event handlers is not necessary in Xamarin Forms for iOS, as it is in a non-forms iOS app when inheriting from NSObject. However, I am surprised by this conclusion so I would like help verifying.

Here's what I did in more detail.

Here is the test project I created: https://github.com/nathanielcook/XFormsDisposeTest

Open it and run it (or profile it if you prefer--either way keep an eye also on the application output window). Click the button to push the view controller, then pop it. Notice that ViewController1 is disposed.

Now search for //SWITCHBUTTON and switch those two lines. Repeat the steps and you'll see that ViewController1 is not disposed. That's because CustomButton inherits from NSObject and we're using a statement lambda. Make that statement lambda a named method and unsubscribe the event in ViewWillDisappear and voila, ViewController1 is disposed. This is exactly why the Xamarin documentation tells us about. For this reason many people just avoid statement lambdas across the board and always unsubscribe events on ViewWillDisappear (or OnDisappearing in Xamarin Forms).

However, I tried the same thing with Xamarin Forms and Dispose is always called. (Again, check the application output window.) To test search for //SWITCHFORMS and switch those two lines. Push Page1, which uses a CustomView that inherits from ViewRenderer with statement lambdas, then pop it and it disposes fine. Push Page2, which uses an iOS PageRenderer with statement lambdas and--this is what surprised me the most--when you pop it it also disposes. So Xamarin Forms seems to do something differently.

Note: In HeapShot if you filter for UIViewController you'll notice that PageRenderer1 and PageRenderer2 are still in memory after popping Page1 and Page2. However, something called a ParentingViewController decrements correctly from 2 to 1 each time. Also, and this is the important part: Unsubscribing from named events or eliminating event handlers all together has no effect whatsoever on the HeapShot results. I even removed the button and made it a standard label with no event handlers, and got the same results. So either PageRenderer1 and PageRenderer2 staying in memory is a Xamarin bug or that is simply expected behavior. (Perhaps it's some sort of performance optimization?) Point being: Until I hear otherwise I can only conclude that statement lambdas in Xamarin Forms are fine, since their presence or absence don't seem to have an effect one way or another on the results.

Ok, so now tell me what the flaws in my testing are. :-)


Viewing all articles
Browse latest Browse all 58056

Trending Articles