Say that I have a class like:
public class Test
{
public Func<string, bool> DoSomething { get; set; }
}
I have some other code that dynamically parses a string and compiles a delegate.
To set the stage, i have another application on another server that needs to execute this code so I want to serialize it and send it over the wire for execution. I could send the string that contains the information i need to recreate the delegate, but creating the delegate seems like an expensive operation seeing that I will have to repeatedly perform that operation again and again. Is there anyway to serialize that delegate?
If you worry about parsing the same string and compiling the result over and over, then you should use caching.
Just have cache implemented using something like
Dictionary<string, YourDelegate>on the server. When you receive a string, check for it in the cache and if it’s not present, create the delegate.If the string is too long (which would mean calling
GetHashCode(), which is used byDictionary, on it would take too long), you could assign some ids or names to the delegates:Client creates the string and a unique id for it (possibly
Guid). It sends a message to the server saying: “here is a specification for delegate with this id”. And then another saying: “use delegate with this id”. The second message could then be called repeatedly.