3

我正在尝试通过一个管理断路器投票策略的辅助函数发出 httpclient 请求。

我试着这样称呼它var response = clientFactory.MakeRequest(() => client.GetAsync("/"));

在客户端工厂内部,我定义了断路器策略,我正在尝试使用该策略执行上面的 lambda,如下所示

public async Task<HttpResponseMessage> MakeRequest(Func<HttpResponseMessage> request)
  {
     var response = policy.ExecuteAsync(() => request.Invoke());
     return response;
  }

作为一个整体,我对 Lambda 相当陌生,将它作为函数传递会变得更加混乱。如何配置函数和第一行代码来执行客户端并返回HttpResponseMessage?我不认为Task<HttpResponseMessage>Func<HttpResponseMessage>不正确

4

1 回答 1

2

我建议你阅读一些关于 async/await(不是 lambdas)的信息,因为这是理解如何实现它的关键。

https://docs.microsoft.com/en-us/dotnet/csharp/async

您正在使用异步编程,因此必须决定是要使用异步方法 MakeRequest 还是要同步方法。如果你想要同步(但是 - 不需要使用 ExecuteAsync。我想,有 Execute() 替代)简单的写:

public HttpResponseMessage MakeRequest(Func<HttpResponseMessage> request)
  {
     var response = policy.ExecuteAsync(() => request.Invoke());
     return await response;
  }

如果你想要异步:

public async Task<HttpResponseMessage> MakeRequest(Func<HttpResponseMessage> request)
{
    var response = policy.ExecuteAsync(() => request.Invoke());
    return response;
}

public void MyMethodUsingAsync()
{
    var responsePromises = MakeRequest(() => {...});
    ///do some job wich will be done before response is retrieved (not waiting for it); and if you need it - use await
    var responseReceived = await responsePromises;
}
于 2017-08-14T19:54:05.037 回答