Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net: Can a delegate ("Action") be serialized into control state?

I am implementing a user control that has a method that takes an Action delegate as a parm.

Attempting to store the delegate in Control State yields a serialization error. Is it even possible to serialize a delegate into Control State?

BP

like image 246
theBruce Avatar asked Dec 22 '09 17:12

theBruce


2 Answers

Not easily - and it could open the door for potential problems.

It is theoretically possible to use reflection to determine which method of an object the delegate is invoking, and write a custom serialization process for it. Upon deserialization you would once again need to write logic to convert the information into a delegate reference.

The problem is that in the general case, discovering the object at runtime that you need to re-generate the delegate for is not always possible. If the delegate refers to a lambda or anonymous method that complicates things even more because their may be closures involved.

You are probably better off either:

  1. Not preserving the Action delegate between requests and having the ASP.NET code re-attach the delegate on postback. This is the least risky option IMHO.

  2. Storing the delegate reference in session state and reattach it to the deserialized object on postback. This option is risky for two reasons:

    a) holding on to object references indefinitely in memory if the end user never posts back, or you forget to clear the object from server state.

    b) if the delegate references page elements (controls, etc) you may run into subtle bugs because the delegate will operate against the objects from the previous request, and not the new request.

like image 89
LBushkin Avatar answered Oct 05 '22 13:10

LBushkin


In this post the author serializes an Action object to be executed later in time. You can extend at your own action serializing to a string instead to a file.

Very interesting:

http://mikehadlow.blogspot.com/2011/04/serializing-continuations.html

like image 30
matgerva Avatar answered Oct 05 '22 11:10

matgerva