Delegates serialization: Limits

When I heard about delegates’ serializability for the first time, my reaction was romantic. I dreamt about some mystical process that serializes delegate’s IL and about other magical things. It is, of course, absolute nonsense, but I love those fairy tales :).

All delegates in C# are inherited directly or indirectly from Delegate. Delegate class is class like any other. It is just marked as serializable – no black magic is needed.

What is buried there?

Basically, there are two properties: Method (MethodInfo) and Target (object). It is all what is needed to invoke any .NET method. When delegate points to a static method, then the Target property is null. There are some other internal details that I don’t understand but I hope they are irrelevant.

These facts reveal weaknesses of delegates’ serialization:
  1. Target property is serialized as well when using binary formatter. It could lead some serious issues when object referenced by Target is part of complex object graph. On the other side if Target is not serialized then the delegate cannot be deserialized at all – there wouldn’t be any suitable instance to make a method call.
  2. Versioning issues.
  3. State of static class is not serialized. Delegate of method that is using static fields (directly or indirectly) is deserialized into completely different context.
In addition to these disadvantages, there is a limitation associated with anonymous delegate that is closed over a variable. It is simply not serializable.

It is clear that “persistable continuation” implemented in C# by delegate serialization as it was suggested by Mike Hadlow would be very limited, which is a pity.

1 comment:

  1. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.