I want to re-use my code with many APM-style async methods. Each method has a BeginXXX and an EndXXX signature pair. I want to reuse the same callback in each of the functions.
I have always used anonymous methods like the one below, but I'm not sure how to extract it into a reusable form. I know this should be easy, but I can't figure out how to use a delegate to make this happen. (this is what I get for being self taught)
var result = tableSymmetricKeys.BeginExecuteQuerySegmented(query, token, opt, ctx, (o) =>
{
var response = (o.AsyncState as CloudTable).EndExecuteQuerySegmented(o);
token = response.ContinuationToken;
int recordsRetrieved = response.Results.Count;
totalEntitiesRetrieved += recordsRetrieved;
Console.WriteLine("Records retrieved in this attempt = " + recordsRetrieved + " | Total records retrieved = " + totalEntitiesRetrieved);
evt.Set();
}, tableSymmetricKeys);
How do I extract the anonymous method with (o) => ...
into a delegate and make it reusable?
You would create a class that has all of your "captured" variables as pass that along as state:
Then, you would create a delegate like this:
Finally, you call it like this: