views:

104

answers:

1

In .NET (at least <=2) there's a problem serializing objects that raise events when those events are handled by a non-serializable object (like a Windows Form).

Because of the way VB.NET implements events, when you serialize an object, its events get serialized too (because events are actually implemented using hidden multicast delegate fields). A side effect of this is that any object which handles events raised by the object being serialized will be considered part of the object graph and will be serialized too.

Some workarounds could be found, implementing custom serialization or using delegates instead of events:

However none of them seems to completely satisfy the authors and users.

Does the .NET 3 / 4 solve this problem?

+3  A: 

Events are handled by creation of a delegate member. If you explicitly define this member yourself, you should be able to add the NonSerialized attribute to it. See this thread for a reference.

For example:

Public Delegate Sub MyEventDelegate()

<NonSerialized()>Private m_MyEventDelegate As MyEventDelegate

Public Custom Event MyEvent As MyEventDelegate
    AddHandler(ByVal value As MyEventDelegate)
        m_MyEventDelegate = DirectCast(System.Delegate.Combine(m_MyEventDelegate, value), MyEventDelegate)
    End AddHandler

    RemoveHandler(ByVal value As MyEventDelegate)
        m_MyEventDelegate = DirectCast(System.Delegate.Remove(m_MyEventDelegate, value), MyEventDelegate)
    End RemoveHandler

    RaiseEvent()
        If m_MyEventDelegate IsNot Nothing Then
            m_MyEventDelegate.Invoke()
        End If
    End RaiseEvent
End Event
Paul Williams
Thanks for the syntax. I don't think I've ever seen the `RaiseEvent` syntax.
John Saunders