异步方法不识别 yield return 方法?

Async method does not recognize yield return method?

问题

当我尝试在异步方法中调用我的 "normal" 方法时,它会被 Debugger1.

忽略

这是我的异步方法

 internal async static Task<DefinitionsModel> DeserializeAsync(this string path)
 {
        var model = new DefinitionsModel();
        var content = await File.ReadAllTextAsync(path);

        model.Pages = content.GetPages();

        return model;
 }

这是我的"normal"方法

private static IEnumerable<PageModel> GetPages(this string content)
{            
        var level = 0;
        var value = nameof(PageModel.Page).GetDElement<PageModel>();
        var start_with_line = $"{level} {value} ";
        var end_with_line = string.Concat(Enumerable.Repeat(Environment.NewLine, 2));

        var expression = $@"\b{start_with_line}\S * {end_with_line}\b";
        var matches = content.GetPagesFromContent(expression);


        yield return new PageModel();
}

辅助图片

yield 除非被枚举,否则不会屈服。在这种情况下:

model.Pages = content.GetPages();

没有枚举。但是你可以这样做:

model.Pages = content.GetPages().ToList();

您通过使用 foreach 语句或 LINQ 查询使用迭代器方法,不出所料 ToList() 使用 foreach.

迭代 IEnumerable

老实说,我正在努力弄清楚你在做什么,很可能需要重新考虑 GetPages

yield (C# Reference)

When you use the yield contextual keyword in a statement, you indicate that the method, operator, or get accessor in which it appears is an iterator. Using yield to define an iterator removes the need for an explicit extra class (the class that holds the state for an enumeration, see IEnumerator for an example) when you implement the IEnumerable and IEnumerator pattern for a custom collection type.

You use a yield return statement to return each element one at a time.

You consume an iterator method by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

您的 GetPages 方法 returns 和 IEnumerable<T>yield return。编译器根据该代码构建状态机。

只有在调用并迭代生成的状态机中使用 GetEnumerator() 方法获得的枚举器后,才会执行该代码。