[英]Call a paginated service asynchronously c#
正在從我的方法調用以下服務
https://myservice?index=0&rows=500
index:查詢結果集中的偏移量。 服務將從這個偏移量返回結果。 默認值為 0,即從第一個結果開始。
rows:每個請求要返回的結果數。 默認為 10,最大數量為 500
我需要繼續分頁,直到開始參數達到響應 JSON 中的 totalRows 計數。 假設如果記錄總數為 10,000,我需要調用該服務 20 次
是否可以修改代碼以使第一個之后的后續服務調用異步以提高性能
public List<FinalOutputDetails> GetFinalOutput()
{
List<FinalOutputDetails> FinalOutput = new List<FinalOutputDetails>();
int totalRows = 500;
int index = 0;
int end = 500;
while (index <= totalRows)
{
string result =CallRemoteService(); // call service https://myservice?index=0&rows=500
var patrialResultDetails = JsonConvert.DeserializeObject<ServiceResultDetails>(result);
totalRows = patrialResultDetails.totalRows;
FinalOutput.AddRange(patrialResultDetails);
start += 500;
end += 500;
}
return FinalOutput;
}
是的,可以,輕松將 CallRemoteService() function 設為
async Task<string>CallRemoteService()
這意味着在第一次或其他調用返回結果之前可以多次調用此方法。
並稱其為異步
Task.Run(async () => string result =await CallRemoteService() ... and do other job to add result to main total string builder here..);
有了這條線,您的應用程序將不會等待結果..
但我必須通知你。 您將失去您的訂單。 如果您需要正確的順序,這意味着您必須等待第一個結果,然后再調用第二個結果。 但這意味着你的問題是錯誤的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.