3

I'm wondering if its possible to create some kind of generic list of actions/funcs, each with different in/out params.

The reason I need this is I have an executer who's job is getting data from an API, each of the methods in that executer goes to a different path in that API, and I want to be able to schedule those requests so I won't overload that API (they will just block me if I pass their threshold of requests).

So each time a method in that executer is called, I will add that method and its params to a list, and another thread will run over the list and execute methods from there using some timeout.

I have to have this logic in the executer and not from it's caller.

So basically wondering if I can do something like:

List<Func<T,T>> scheduler;

Without declaring the types on creation but instead add different types during runtime.

If there is a better solution or pattern for this please do enlighten me.

[edit] obviously I don't want to implement something like:

Func<List<object>, object> scheduler
AlexD
  • 4,062
  • 5
  • 38
  • 65

2 Answers2

3

You can make a List<Tuple<Type, Delegate>> to store your functions.

The below code runs fine:

var scheduler = new List<Tuple<Type, Delegate>>();

scheduler.Add(
    Tuple.Create<Type, Delegate>(
        typeof(Func<int, int>),
        (Func<int, int>)(n => n + 1)));

scheduler.Add(
    Tuple.Create<Type, Delegate>(
        typeof(Func<string, string, int>),
        (Func<string, string, int>)((x, y) => x.Length + y.Length)));

You would then need to use reflection to bring them back from being a Delegate.

This would be a good starting point.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0

If you know the parameter values at the time of adding the func to the list, you can simply capture them in a lambda that applies the Func<T, X, Y, Z ...> and thus reduce it to a Func<T>, e.g.

Func<T, X> funcToAdd = ...
Func<T> wrapper = () => funcToAdd(valueForX);
myFuncList.Add(wrapper);

The type of the func list can then just be List<Func<T>>

Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46
  • How is the declaration of the list looks like? I can't keep it List>, I have to specify a type – AlexD Aug 16 '15 at 10:06
  • What are you trying to do with the return values? If the funcs can return anything you can't do any better than `Func` AFAICT – Jonas Høgh Aug 16 '15 at 10:26