gpt4 book ai didi

c# - 如何与多个 APM BeginXXX 调用共享 AsyncCallback?

转载 作者:行者123 更新时间:2023-11-30 16:21:14 24 4
gpt4 key购买 nike

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

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

 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) => ... 的匿名方法提取到委托(delegate)中并使其可重用?

最佳答案

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

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
}

然后,您将像这样创建一个委托(delegate):

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

关于c# - 如何与多个 APM BeginXXX 调用共享 AsyncCallback?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13436436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com