【问题标题】:What is the best way to load multiple remote RSS feeds?加载多个远程 RSS 提要的最佳方式是什么?
【发布时间】:2013-04-18 19:22:47
【问题描述】:

我正在做一个项目,我需要加载多个(100 多个)远程 RSS 提要,解析它们并查询一些关键字。 显然这个过程很耗时,我正在寻找实现这一点的最佳方法。

我当前的实现同步加载提要,因为使用 TPL 的异步实现失败了,因为在此过程中创建了许多任务,最后它抛出了一个异常。

用于加载远程提要的异步部分如下所示:

/// <summary>
/// Loads the specified URL.
/// </summary>
/// <param name="url">The URL.</param>
/// <returns></returns>
/// <exception cref="ScanException">Unable to download rss feed from the specified url. Check the inner exception for more details.</exception>
protected async Task<XDocument> Load(string url)
{
    XDocument document = null;

    try
    {
        using (var client = new HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();
                document = XDocument.Parse(content);
            }
        }
    }
    catch (Exception ex)
    {
        throw new ScanException(url, "Unable to download rss feed from the specified url. Check the inner exception for more details.", ex);
    }

    return document;
}

我希望你们能指出我正确的方向,这样我就可以让它正常工作(性能方面)。

最后一个问题是:加载多个远程 RSS 提要的最佳方式是什么?

测试代码

/// <summary>
        /// Reads the feeds by batch async.
        /// </summary>
        /// <param name="feeds">The feeds.</param>
        public void ReadFeedsByBatchAsync(string[] feeds, TorrentStorage storage, int batchSize = 8)
        {
            var tasks = new List<Task>(batchSize);
            var feedsLeft = feeds.Length;

            foreach (string feed in feeds)
            {
                var readFeedTask = this.client.GetStringAsync(feed);

                if (readFeedTask.Status == TaskStatus.RanToCompletion)
                {
                    XDocument document = XDocument.Parse(readFeedTask.Result);
                    var torrents = ProcessXmlDocument(document);

                    storage.Store(torrents);
                }

                tasks.Add(readFeedTask);
                --feedsLeft;

                if (tasks.Count == tasks.Capacity || feedsLeft == 0)
                {
                    var batchTasks = tasks.ToArray();
                    tasks.Clear();

                    try
                    {
                        Task.WaitAll(batchTasks);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }


        }

【问题讨论】:

    标签: c# asynchronous rss task-parallel-library async-await


    【解决方案1】:

    我已经在我的 GitExtensions 分支中解决了一个类似的问题。我通过创建任务来分批 8 个 REST API 调用,并为每批 8 个任务执行一个 Task.WaitAll。这有点简单,但它可以在不使代码过于复杂的情况下完成这项工作:

    https://github.com/PombeirP/gitextensions/blob/BuildServerIntegration/Plugins/BuildServerIntegration/TeamCityIntegration/TeamCityAdapter.cs#L178.

    我建议的一件事是重用 HttpClient 类。总是为每个请求创建一个新实例似乎有点矫枉过正。

    【讨论】:

    • 谢谢,我要试试这个。我会让你知道事情的结果。
    • 我对异步编程不是很有经验,但是你能告诉我在 Task.WaitAll 之后我应该做什么吗?任务创建成功,我可以看到它们在 WaitAll 之后包含数据,但是我应该如何处理数据?
    • 完成后,只需访问其 Result 属性即可获得结果。你可以 var results = tasks.Select(t => t.Result);如果你愿意
    • 好吧,我试过了,但没有 Result 属性。检查我的问题中的屏幕截图
    • 要访问他们的结果,您可以尝试:Task.ContinueWhenAll(inputTasks, completedTasks =&gt; { ... }); 或 Task.WaitAll(inputTasks);      inputTasks.Select(task =&gt; task.Result) ...,具体取决于您的需要。例如,在我向您指出的代码中,我不需要在它们全部完成后访问 Task.Result,因为我在每个任务完成时单独处理结果。
    【解决方案2】:

    恕我直言,当您遇到此类问题时,最简单的方法是编写同步代码,然后在输入集合上编写 Parallel.ForEach。

    它对线程不太友好,但您可以非常简单地设置最大并行度,包括在调试期间将其设置为 1。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 2010-09-10
      • 2012-09-02
      • 2015-10-14
      相关资源
      最近更新 更多