有没有一种方法可以异步处理多个xml feed?

时间:2020-06-17 09:49:03

标签: asynchronous task odata xmlreader atom-feed

我正在使用Atom10FeedFormatter类来处理调用OData Rest API端点的原子xml提要。

工作正常,但是如果Feed中有200多个条目,则api会使结果变慢。

这就是我所使用的:

import abc.xyz.Constant._

我希望通过拆分原始请求以跳过一些条目并限制条目大小来查询结果,从而至少加快一点速度。

主要思想是使用$ count计算提要的数量,将提要的结果划分为20个块,在端点url中使用$ skip和$ top,遍历结果,最后对其进行总结。

        Atom10FeedFormatter formatter = new Atom10FeedFormatter();

        XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";

        string odataurl= "http://{mysite}/_api/ProjectData/Projects";

        using (XmlReader reader = XmlReader.Create(odataurl))
        {
             formatter.ReadFrom(reader);
        }

         foreach (SyndicationItem item in formatter.Feed.Items)
         {
              //processing the result
         }

通常我会使用对api的异步调用(这种情况下numberofblocks = 26个并行调用),但是我不知道该怎么做。 int countoffeeds = 500; // for the sake of simplicity, of course, i get it from the odataurl using $count int numberofblocks = (countoffeeds/20) + 1; for(int i = 0; i++; i<numberofblocks){ int skip = i*20; int top = 20; string odataurl = "http://{mysite}/_api/ProjectData/Projects"+"?&$skip="+skip+"&top=20"; Atom10FeedFormatter formatter = new Atom10FeedFormatter(); using (XmlReader reader = XmlReader.Create(odataurl)) { formatter.ReadFrom(reader); // And this the part where I am stuck. It returns a void so I //cannot use Task<void> and process the result later with await } ... 返回void,因此我无法在Task中使用它。

该如何解决?如何同时读取多个xml提要?

1 个答案:

答案 0 :(得分:1)

通常我会使用对api的异步调用(这种情况下numberofblocks = 26个并行调用),但是我不知道该怎么做。 formatter.ReadFrom返回void,因此无法与Task一起使用。

Atom10FeedFormatter目前是一种过时的类型,它不支持异步。也不可能对其进行更新以支持异步。

该如何解决?如何同时读取多个xml提要?

由于您陷入了同步世界,因此您可以选择使用“伪异步”。这仅意味着您将在线程池线程上执行同步阻塞工作,并将这些操作视为异步操作。即:

var tasks = new List<Task<Atom10FeedFormatter>>();
for(int i = 0; i++; i<numberofblocks) {
  int skip = i*20;
  int top = 20;
  tasks.Add(Task.Run(() =>
  {
    string odataurl = "http://{mysite}/_api/ProjectData/Projects"+"?&$skip="+skip+"&top=20";
    Atom10FeedFormatter formatter = new Atom10FeedFormatter();
    using (XmlReader reader = XmlReader.Create(odataurl))
    {
      formatter.ReadFrom(reader);
      return formatter;
    }
  }));
}
var formatters = await Task.WhenAll(tasks);