【问题标题】:How do I await action response in a loop c#如何在循环 c# 中等待动作响应
【发布时间】: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


【解决方案1】:

不,TaskCompletionSource 不脏。我认为这是要走的路。

我只会返回任务本身,而不是在这个方法中等待它(不是异步方法)。等待的决定可以升级。您可能想要等待多个呼叫。对于直接返回true,您可以使用Task.FromResult()

【讨论】:

  • 感谢您的反馈,API 不支持任务,因此我对此感到满意,尽管我认为将其提升一个级别可能是一个不错的选择。
  • 如果 API 不支持任务,您可以自己创建它。只需使用 TaskCompletionSource 并在 Task.Run 上运行 API 调用。
猜你喜欢
  • 2019-07-18
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-27
相关资源
最近更新 更多