【发布时间】:2019-08-22 08:54:46
【问题描述】:
我们有一个要循环的集合,我们需要对集合中的每个项目进行服务调用,并在执行集合中的下一个服务调用之前等待响应。
问题是我无法在执行集合中的下一个项目之前等待响应,我确实设法通过使用 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 之前等待响应。
【问题讨论】:
-
如果您调用的 API 不支持任务,那么使用
TaskCompletionSource并没有什么不妥,这正是您应该做的。
标签: c# wcf xamarin async-await action