10

I have a series of functions that I want to have the following functionality.

  • When the function is called, add itself to a list of functions remembering the parameters and values
  • Allow the list of functions to be called at a later date

The different functions have a variety of different parameters and I'm struggling to think of an elegant way to do this. Any help would be appreciated.

5
  • Will all these functions have the same signatures or will they be different? Will you be recalling these functions with the same arguments or will they change? Dec 21, 2011 at 1:50
  • @JeffMercado They will be different with a variable number of parameters and return types. Dec 21, 2011 at 1:51
  • 2
    Maybe take a look at this question. stackoverflow.com/questions/377217/… It may not be exaclty the same thing you are trying to do, but it talks about running delegates with differing parameters. Dec 21, 2011 at 2:04
  • So I've been reading between the lines but are you just trying to create a class to facilitate memoization? It will cache return values for different parameters and not actually call the methods a second time. Is this what you're trying to do or do you have to be able to call them again? Dec 21, 2011 at 3:13
  • @JeffMercado I do actually want to call them again, it's actually designed to record a series of functions then replay them (possibly multiple times) at the users request. Dec 21, 2011 at 5:36

5 Answers 5

10

I think this would meet your needs, however the functions are not "adding themselves".

public class Recorder
{
    private IList<Action> _recording;
    public Recorder()
    {
        _recording = new List<Action>();
    }
    public void CallAndRecord(Action action)
    {
        _recording.Add(action);
        action();
    }
    public void Playback()
    {
        foreach(var action in _recording)
        {
            action();
        }
    }
}

//usage
var recorder = new Recorder();
//calls the functions the first time, and records the order, function, and args
recorder.CallAndRecord(()=>Foo(1,2,4));
recorder.CallAndRecord(()=>Bar(6));
recorder.CallAndRecord(()=>Foo2("hello"));
recorder.CallAndRecord(()=>Bar2(0,11,true));
//plays everything back
recorder.Playback();

One way to make the functions "add themselves" would be to use an AOP lib such as postsharp or linfu dynamic proxy, and add an interceptor which adds the function and args to the array. To do this would probably be more work than it would be worth IMO, as the above is much simpler and still achieves the desired functionality.

2
  • This answer is problematic if variables are passed as parameters to the recorded functions. If the variable in question changes between the call to CallAndRecord and the call to Playback, the changed value will be used in playback.
    – TreDubZedd
    Aug 6, 2014 at 14:25
  • @TreDubZedd True, in my example I used all value types for which this is not an issue, but if reference types are used the caller will need to be careful to treat anything passed in as immutable, otherwise side effects would ensue. If you wanted to protect against this you would need to be sure your params implement ICloneable (or some other equal cloning method) and then traverse the expression and clone all the params, and then do all your invocation with reflection etc. It gets very complicated very quickly, but I think this solution is the "bang for the buck" the OP was looking for.
    – Brook
    Aug 16, 2014 at 14:02
5

There's hardly an elegant solution to this. Since you said the methods would all have different signature, there's no way to store them in a single array as delegates. With that out of the way, next you can try is using reflection, storing each parameter value in object[], storing the method as MethodInfo, and then invoking it.

Edit: This is what I could come up with:

    private Dictionary<MethodBase, object[]> methodCollection = new Dictionary<MethodBase, object[]>();

    public void AddMethod(MethodBase method, params object[] arguments)
    {
        methodCollection.Add(method, arguments);
    }

    private void MyMethod(int p1, string p2, bool p3)
    {
        AddMethod(System.Reflection.MethodInfo.GetCurrentMethod(), new object[] { p1, p2, p3 });
    }

    private void MyOtherMethod()
    {
        AddMethod(System.Reflection.MethodInfo.GetCurrentMethod(), new object[] { });
    }

Then just invoke with method.Invoke(method.ReflectedType, args)

2
  • +1 This is more what I was trying to say... but do it with DynamicInvoke. I've never actually used it before though, so I could be way off base. Dec 21, 2011 at 2:29
  • To use DynamicInvoke you need Delegate instance for which you need a Type and MethodInfo so you can create delegate with Delegate.CreateDelegate(), which is basically the same thing, just few more steps. You still need reflection. Dec 21, 2011 at 2:37
3

Maybe you could some how use the Delegate.DynamicInvoke(Object[] obj) function. You could add each method to an object array, then loop through the array calling DynamicInvoke on each one.

1

I'm not sure I understand your question, but I think you could use array of pointers to a functions(in C# it is called delegates). So when function is called, put function pointer in a list. In this way you can call function from list. Here is some idea. Notice when you add new delegate pointer to a list (functionPointers), in second list myParameters you add new object of type Parameters which holds function parameters in public attribute called parameters. This means that delegate i in list functionPointers for parameters has i-th object in list myParameters. This is how you know which parameters, are for which function. Probably there are some betters solutions, but this is alternative.

delegate void NewDelegate();
class Parameter{
     public ArrayList parameters;

}
ArrayList functionPointers=new ArrayList();
ArrayList<Parameter> myParameters=new ArrayList<Parameter>();
NewDelegate myDelegate;

void someFunction(int a, int b){
   myDelegate+=someFunction;//you add this function to delegate because this function is called
   functionPointers.add(myDelegate);//Add delegete to list
   Parameter p=new Parameter();//Create new Parameter object
   p.parameters.add(a);//Add function parameters
   p.parameters.add(b);
   myParameters.add(p);//add object p to myParameters list

}

1
  • This code does not even compile. You can't store any method to a parameterless delegate. You have to follow the method signature rules. Dec 21, 2011 at 2:41
1

You could consider using a list of actions or functions

using System;
using System.Collections.Generic;

namespace ReplayConsole
{
class Program
{
    private static IList<Action> _actions;

    static void Main(string[] args)
    {
        _actions = new List<Action>
                   {
                       () => {
                           //do thing 
                       },
                       () => {
                           //do thing 
                       },
                       () => {
                           //do thing 
                       },
                       () => {
                           //do thing 
                       },
                   };

        foreach (var action in _actions)
        {
            action();
        }
    }
}

if you want to store parameters as well and have you could use a Func and store and use it in much the same way

You could also look at Tasks

EDIT:

looking at the answers that popped up while I was writing mine this solution is very similar to Brook's

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.