我们有一个要循环的集合,我们需要对集合中的每个项目进行服务调用,并在执行集合中的下一个服务调用之前等待响应。
问题是我无法在执行集合中的下一个项目之前等待响应,我确实设法通过使用 TaskCompletionSource 触发结果来使其工作,但这看起来很脏。有更好的方法吗?
我尝试过使用“Func oftype Task”,但似乎无法使其正常工作。
public async Task<bool> PerformRTV(string policyId)
{
if (!Instance.RTVDone)
{
var result = new TaskCompletionSource<bool>();
PerformValuation(policyId, resp =>
{
if (!(resp.Error is null))
{
ErrorService.LogError(resp.Error);
result.SetResult(false);
return;
}
if (!resp.Result)
{
result.SetResult(false);
return;
}
result.SetResult(true);
return;
});
return await result.Task;
}
else
{
return true;
}
}
private void PerformValuation(string policyId, Action<#########CompletedEventArgs> response)
{
Service.HookResponseHandlerToServiceEvent(_portfolioServiceClient, nameof(_portfolioServiceClient.#########Completed), response);
_portfolioServiceClient.#########RTVAsync(policyId, ApplicationSettings.Authentication.TPCodeID);
}
简而言之,我在循环中调用 PerformRTV,并希望在使用循环中的下一项调用 PerformRTV 之前等待响应。
最佳答案
不,TaskCompletionSource 不脏。我认为这是要走的路。
我只会返回任务本身,而不是在此方法中等待它(不是异步方法)。等待的决定可以更上一层楼。您可能需要等待多个电话。要直接返回 true
,您可以使用 Task.FromResult()
关于c# - 如何在循环中等待操作响应 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57605551/