3

我想通过许多 APM 风格的异步方法重用我的代码。每个方法都有一个 BeginXXX 和一个 EndXXX 签名对。我想在每个函数中重用相同的回调。

我一直使用像下面这样的匿名方法,但我不确定如何将其提取为可重用的形式。我知道这应该很容易,但我不知道如何使用委托来实现这一点。(这是我自学得到的)

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

如何将匿名方法提取(o) => ...到委托中并使其可重用?

4

1 回答 1

3

您将创建一个包含所有“捕获”变量的类,并将其作为状态传递:

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
}

然后,您将创建一个像这样的委托:

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.
}

最后,你这样称呼它:

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

var result = tableSymmetricKeys.BeginExecuteQuerySegmented(query, token, opt, ctx,asyncCallback, state);
于 2012-11-18T01:07:45.123 回答