Reputation: 809
I am trying to chain a bunch of functions calls into one callback function ptr (using Action) and each of those function calls take different arguments (so can't use delegates which would be ideal, unless I am missing something :)) So this is what I did:
for (int i=0; i<num_func_calls; ++i)
{
// could be anything different for each call
int call_id = i;
Action old_action = lastAction;
lastAction = new Action(() =>
{
FuncCall(call_id, true);
old_action();
});
}
It works as I expect it to, but the question is: is this efficient/correct? Are there any gotcha's or things I need to worry about with this?
Thanks!
Upvotes: 1
Views: 1580
Reputation: 78262
Here is an example using higher order functions.
static Action Apply(IEnumerable<int> data)
{
Action zero = () => { };
return data.Aggregate(zero,
(a, id) => a + (() => FuncCall(id, true)));
}
Upvotes: 2
Reputation: 48086
I'm not entirely sure what it is you're asking but I'm just going to address a couple of things in your post which are wrong.
Firstly; Action
is a Delegate
it's just one that accepts a single parameter and does not return a value. If I have some Action
call it A
- Delegate d = A;
will compile and run.
Secondly, to pass args in a general manner (meaning to some arbitrary function) you can use DynamicInvoke
and wrap your arguments in an object array. As long as the items in the array are of the right types and are in the right order the method will correctly execute. Otherwise it will throw.
DynamicInvoke has a specific application but as an example if you provide me with an Object[]
and a Delegate
I can use DynamicInvoke
to invoke the function without knowing what it's definition is. Like;
myDelegate.DynamicInvoke(args); // where args is an Object[]
In general, you only want to use it when you're deciding which delegates to call at run time.
Upvotes: 0
Reputation: 86084
This would be a great case to use a Task
, since it has .ContinueWith
which tells the task to run another task when it's complete. You can chain them together.
http://msdn.microsoft.com/en-us/library/dd270696.aspx
Also, you could reduce the delegate use by doing this:
() => {
for (int i=0; i<num_func_calls; ++i) FuncCall(i, true);
}
Upvotes: 0