<p>Is there an advantage to dynamically attaching/detaching event handlers?</p>

<p>Would manually detaching handlers help ensure that there isn't a reference remaining to a disposed object?</p>

[{'answer_id': 57571, 'author': 'jdecuyper', 'author_id': 296, 'author_profile': 'https://Stackoverflow.com/users/296', 'pm_score': 0, 'selected': False, 'text': '<p>Most of the time the framework takes care of that for you.</p>\n'}, {'answer_id': 57590, 'author': 'Tobi', 'author_id': 5422, 'author_profile': 'https://Stackoverflow.com/users/5422', 'pm_score': 0, 'selected': False, 'text': '<p>Manually detaching an event can be important to prevent memory leaks: the object that connects to an event fired by another object, will not be garbage collected until the object that fires the event is garbage collected. In other words, an "event-raiser" has a strong reference to all the "event-listeners" connected to it.</p>\n'}, {'answer_id': 57598, 'author': 'rpetrich', 'author_id': 4007, 'author_profile': 'https://Stackoverflow.com/users/4007', 'pm_score': 1, 'selected': False, 'text': '<p>I find that dynamically attaching/detaching event handlers is only of use where you have a long-lived object exposes events that are consumed by many short-lived objects. For most other cases the two objects are disposed around the same time and the CLR does a sufficient job of cleaning up on its own</p>\n'}, {'answer_id': 57605, 'author': 'OwenP', 'author_id': 2547, 'author_profile': 'https://Stackoverflow.com/users/2547', 'pm_score': 2, 'selected': False, 'text': "<p>I'm pretty sure that the <code>Handles</code> clause is just syntactic sugar and inserts an <code>AddHandler</code> statement into your constructor.  I tested using this code and disabled the application framework so the constructor wouldn't have extra stuff:</p>\n\n<pre><code>\nPublic Class Form1\n\n    Public Sub New()\n        ' This call is required by the Windows Form Designer. '\n        InitializeComponent()\n\n        ' Add any initialization after the InitializeComponent() call. '\n        AddHandler Me.Load, AddressOf Form1_Load\n    End Sub\n\n    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n        Dim breakpoint As Integer = 4\n    End Sub\nEnd Class</code></pre>\n\n<p>The IL ended up like this:</p>\n\n<pre><code>  IL_0000:  nop\n  IL_0001:  ldarg.0\n  IL_0002:  call       instance void [System.Windows.Forms]System.Windows.Forms.Form::.ctor()\n  IL_0007:  nop\n  IL_0008:  ldarg.0\n  IL_0009:  ldarg.0\n  IL_000a:  dup\n  IL_000b:  ldvirtftn  instance void WindowsApplication1.Form1::Form1_Load(object,\n                                                                           class [mscorlib]System.EventArgs)\n  IL_0011:  newobj     instance void [mscorlib]System.EventHandler::.ctor(object,\n                                                                          native int)\n  IL_0016:  call       instance void [System.Windows.Forms]System.Windows.Forms.Form::add_Load(class [mscorlib]System.EventHandler)\n\n '... lots of lines here '\n\n  IL_0047:  ldarg.0\n  IL_0048:  callvirt   instance void WindowsApplication1.Form1::InitializeComponent()\n  IL_004d:  nop\n  IL_004e:  ldarg.0\n  IL_004f:  ldarg.0\n  IL_0050:  dup\n  IL_0051:  ldvirtftn  instance void WindowsApplication1.Form1::Form1_Load(object,\n                                                                           class [mscorlib]System.EventArgs)\n  IL_0057:  newobj     instance void [mscorlib]System.EventHandler::.ctor(object,\n                                                                          native int)\n  IL_005c:  callvirt   instance void [System.Windows.Forms]System.Windows.Forms.Form::add_Load(class [mscorlib]System.EventHandler)\n  IL_0061:  nop\n  IL_0062:  nop\n  IL_0063:  ret\n} // end of method Form1::.ctor</code></pre>\n\n<p>Notice two identical blocks of code around IL_000b and IL_0051.  I think it's just syntactic sugar.</p>\n"}, {'answer_id': 57650, 'author': 'Pete', 'author_id': 3059, 'author_profile': 'https://Stackoverflow.com/users/3059', 'pm_score': 3, 'selected': True, 'text': "<p>It's not a question of using AddHandler versus Handles.</p>\n\n<p>If you are concerned about the reference to your event handler interfering with garbage collection, you should use RemoveHandler, regardless of how the handler was attached.  In the form or control's Dispose method, remove any handlers.</p>\n\n<p>I have had situations in Windows Forms apps (.NET 1.1 days) where an event handler would be called on controls that had no other references to them (and which for all intents and purposes were dead and I would have thought been GC'ed) -- extremely hard to debug.</p>\n\n<p>I would use RemoveHandler to get rid of handlers on controls that you are not going to reuse.</p>\n"}, {'answer_id': 74599, 'author': 'CindyH', 'author_id': 12897, 'author_profile': 'https://Stackoverflow.com/users/12897', 'pm_score': 1, 'selected': False, 'text': "<p>I manually attach handlers when I manually create controls (for example, dynamically creating a TextBox for each database record).  I manually detach handlers when they are handling things I'm not quite ready to handle yet (possibly because I'm using the wrong events? :)  )</p>\n"}, {'answer_id': 19306349, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 2, 'selected': False, 'text': '<p>Declaring a field as <code>WithEvents</code> will cause the compiler to automatically generate a property with that name.  The getter returns the value of a backing field.  The setter is a little more complicated.  It first checks whether the backing field already has the correct value.  If so, it exits.  Otherwise, if the backing field is non-null, it issues "RemoveHandler" requests for all its events to the object identified by the backing field.  Next, regardless of whether the backing field was non-null, it sets it equal to the requested value.  Finally, if the new value is non-null, whether the old one was or not, the property issues "AddHandler" requests for all its events to the object identified by the new value.</p>\n\n<p>Provided that one sets all of an object\'s WithEvents members to <code>Nothing</code> before abandoning it, and avoids manipulating WithEvents members in multiple threads, the auto-generated event code will not leak.</p>\n'}]
['https://Stackoverflow.com/questions/57567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4770/']