代码之家  ›  专栏  ›  技术社区  ›  Tim

为异步方法返回列表的最佳方式是什么?

  •  0
  • Tim  · 技术社区  · 2 年前

    我正在使用此示例编写RSS阅读器 https://github.com/dotnet/SyndicationFeedReaderWriter

    我想记录所有 ISyndicationItem 的以列表形式返回。我得到的编译器错误是“error CS1983 async 方法必须为 void , Task , Task<T> ,类任务类型, IAsyncEnumerable<T> IAsyncEnumerator<T> “最理想的方法是什么?

    using Microsoft.SyndicationFeed;
    using Microsoft.SyndicationFeed.Rss;
    using System.Collections.Generic;
    using System.Xml;
    
    static async List<ISyndicationItem> ReadRSSFeed(string inputUri)
    {
        var itemList = new List<ISyndicationItem>();
        using (var xmlReader = XmlReader.Create(inputUri,
            new XmlReaderSettings() { Async = true }))
        {
            var feedReader = new RssFeedReader(xmlReader);
    
            while (await feedReader.Read())
            {
                switch (feedReader.ElementType)
                {
                    // Read category
                    case SyndicationElementType.Category:
                        ISyndicationCategory category = await feedReader.ReadCategory();
                        break;
    
                    // Read Image
                    case SyndicationElementType.Image:
                        ISyndicationImage image = await feedReader.ReadImage();
                        break;
    
                    // Read Item
                    case SyndicationElementType.Item:
                        ISyndicationItem item = await feedReader.ReadItem();
                        itemList.Add(item);
                        break;
    
                    // Read link
                    case SyndicationElementType.Link:
                        ISyndicationLink link = await feedReader.ReadLink();
                        break;
    
                    // Read Person
                    case SyndicationElementType.Person:
                        ISyndicationPerson person = await feedReader.ReadPerson();
                        break;
    
                    // Read content
                    default:
                        ISyndicationContent content = await feedReader.ReadContent();
                        break;
                }
            }
        }
        return itemList;
    }
    
    1 回复  |  直到 2 年前
        1
  •  2
  •   David Browne - Microsoft    2 年前

    只需返回 Task<T> 而不是 T . 在方法内部,您仍然返回 T .

    所以应该是:

    static async Task<List<ISyndicationItem>> ReadRSSFeed(string inputUri)