2017-08-14 77 views
3

我試圖通過幫助函數來管理斷路器polly策略的httpclient請求。通過Lambda Func發出Http請求

我試圖把它像這樣var response = clientFactory.MakeRequest(() => client.GetAsync("/"));

裏面的客戶工廠的,我有我斷路器政策規定,我試圖執行上面的使用政策,像這樣

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

作爲一個整體,我對Lambda的新手相當陌生,並且把它作爲一個函數傳遞給了我更多的困惑。如何配置函數和第一行代碼來執行客戶端並返回HttpResponseMessage?我不認爲Task<HttpResponseMessage>Func<HttpResponseMessage>是正確的

回答

2

我會建議你讀一些關於async/await(不是lambda)的信息,因爲這是理解如何實現它的關鍵。

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

您正在使用異步編程所以必須決定,是否要具有異步方法makeRequest的或你想要同步的。如果你想同步(但後來 - 使用ExecuteAsync沒有必要,我想,有執行()二選一)簡單的寫:

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