How do I share an AsyncCallback with many APM Begi

2019-07-06 00:52发布

问题:

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?

回答1:

You would create a class that has all of your "captured" variables as pass that along as state:

public class QueryState
{
   public CloudTable CloudTable{get;set;}
   public Token Token{get;set;}
   public class ManualResetEvent Evt{get;set;} //i'm guessing that's what this is
   //any other variables you were using
}

Then, you would create a delegate like this:

AsyncCallback asyncCallback = (asyncResult) =>
{
   QueryState state = asyncResult.State as QueryState;
   var response = state.CloudTable.EndExecuteQuerySegmented(asyncResult);
   //rest of method... make sure to use the state variable to get whatever you need.
}

Finally, you call it like this:

var state = new QueryState
{
   CloudTable = tableSymmetricKeys,
   //set everything else
}

var result = tableSymmetricKeys.BeginExecuteQuerySegmented(query, token, opt, ctx,asyncCallback, state);