【问题标题】:Calling a webservice asynchonously异步调用 Web 服务
【发布时间】:2023-03-15 20:43:01
【问题描述】:

我有一种方法如下,它通过网络服务从数据库中获取大量客户数据。该方法返回客户列表如下:

 List<Customer> customers = new List<Customer>();

 foreach (CustomerSummary cs in lastModifiedCustomers)
 {
    customers.Add(customerService.CallService(x => x.GetCustomerByKey(cs.Key, context)));
 }

 return customers;

如何以异步方式调用上面的webservice?我无法对 Web 服务代码进行任何更改。

实际上,在进行 API 调用时,获取如此庞大的数据会导致超时错误。有没有优化的方法来做到这一点?

【问题讨论】:

  • 使用任务类。
  • 你使用Task.Run(()=&gt;customerService.CallService
  • @Eldho webservice方法是同步的。在进行上述更改时,我得到错误:错误 CS1503 Argument 1: cannot convert from 'System.Threading.Tasks.Task' to 'Customer'
  • 你需要等待类似'var cs=await task.run(()=> yourservice.method(1):'这样的结果
  • 这肯定不会改变超时错误。因为在任何情况下服务都有超时设置。如果此超时是您的客户端应用程序超时,那么您可以将其调整为更大的值。

标签: c# asp.net web-services asynchronous synchronous


【解决方案1】:

使用上述解决方案时出现了超出范围的错误。因此我将其更正如下:

int size=100;
List<Customer> customers = new List<Customer>();
for(int i=0;i<iterations;i+=size)
{
 foreach (CustomerSummary cs in lastModifiedCustomers.GetRange(i,Math.Min(size,lastModifiedCustomers.Count-i)))
 {
    customers.Add(customerService.CallService(x => x.GetCustomerByKey(cs.Key, context)));
 }
}
 return customers;

【讨论】:

  • 希望您没有在此修复中引入竞争条件。
【解决方案2】:

试试这样的

int size=1000;
int iterations = (lastModifiedCustomers.Items.Count/size)+1;

List<Customer> customers = new List<Customer>();
for(int i=1;i<iterations;i++)
{

 foreach (CustomerSummary cs in lastModifiedCustomers.GetRange(i==1?i:(i-1)*size+1,size))
 {
    customers.Add(customerService.CallService(x => x.GetCustomerByKey(cs.Key, context)));
 }
}
 return customers;

【讨论】:

  • @DanielBoteroCorrea 这只是问题的一种解决方法,它将针对给定列表多次访问 Web 服务。
  • @Atk 感谢您提供此解决方法。这是有效的。我在 GetRange() 中只进行了一项更改,即我们只需要给出大小,而不是 i*size,因为第二个参数指定计数而不是索引。
  • @kanika 是的,我现在更正了。请接受作为答案并投票。
  • @Atk 还有一件事要问,如果我的记录是 1001 并且我给了 size=100 那么它将如何使用最后一个元素,因为它只会遍历 10 次迭代。
  • @kanika int 迭代次数 = (lastModifiedCustomers.Items.Count/size)+1;例如,1001/100+1 等于 11 次迭代。
猜你喜欢
  • 2011-09-03
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
  • 1970-01-01
相关资源
最近更新 更多