繁体   English   中英

异步调用分页服务 c#

[英]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&amp;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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM