views:

123

answers:

1

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

+1  A: 

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.

LBushkin
Pretty much as I suspected...although, I was willing to give it a try.Solution 1 will require storing some evidence to determine which method/delegate to re-attach.In Solution 1, session will time out after 60 minutes and the delegate will be removed from server state at that time, no?Thanks, BP
theBruce
Session time out will cause the state to be discarded, and with it the delegate and any object graph that delegate is keeping in memory. However, if you're building a site that many users visit, this may strain server resources if that delegate results in a large object graph being kept around between requests. Alo, if you don't clear session state on each response, you can end up with multiple instances in memory (assuming you aren't reusing the session state key). If you reuse the session state key you run the risk of the same user opening a second window/tab and experience a state collision
LBushkin
Based on your comment here, I think I'm fine saving the delegate to session state. (Which works just fine!)Small number of users, tiny object graph, usercontrol is wrapped in an ajax modaldialog, so more than one invocation is not possible. Yea!Thanks again.BP
theBruce