How do I share an AsyncCallback with many APM BeginXXX calls?

折月煮酒 提交于 2019-12-12 14:53:36

问题


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);


来源:https://stackoverflow.com/questions/13436436/how-do-i-share-an-asynccallback-with-many-apm-beginxxx-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!