I have a fairly generic class (Record) that I have added a callback handler to, so I can do something like the following.
record.Save(AfterSaveMethod);
Which also returns the identity number of the record created. The issue I have now is that I have this nested save routine in a loop, and I need to use/pass the i
variable!
for (int i; i < count ;i++)
{
record.Save(AfterSaveMethod2) //but I need to pass i through as well
}
What do I do here?
A\ rewrite the save method and include it in this class (yuk),
B\ have an overloaded save option that takes an object as a parameter, so I can pass it through to my record class, and then merge it with the identity number. Returning both the identity number and anything extra contained in the passed through object (hmm, sounds a bit messy),
C\ is there a sexier option?
You could also create a (thread-static) context object, which stores your "state" (in this case, the index variable value), which you can access using a static property (say
MyContext.Current
). Depends on the complexity of the context ...WCF uses something like this with
OperationContext.Current
, ASP.NET, TransactionScope et al.If the context is a bit more complex than yours and you don't want to pollute the signatures of several methods, I think this model is quite neat.
Use:
(very simplistic sample)
If the context is
[ThreadStatic]
you could have multiple concurrent calls which won't affect each otherThis is where anonymous methods or lambda expressions are really handy :)
Try this (assuming C# 3):
Note that the lambda expression here is capturing
index
, noti
- that's to avoid the problems inherent in closing over the loop variable.