Asp.net: Can a delegate (“Action”) be serialized i

2019-06-19 03:38发布

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

2条回答
虎瘦雄心在
2楼-- · 2019-06-19 04:17

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.

查看更多
地球回转人心会变
3楼-- · 2019-06-19 04:30

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

查看更多
登录 后发表回答