3

PROBLEM

When i try to call my "normal" method in async method , then it gets ignored from Debugger1.

Here is my async method

 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;
 }

and here is my "normal" method

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();
}

HELPER PICTURES

image link

mjwills
  • 23,389
  • 6
  • 40
  • 63
Zer0
  • 1,146
  • 6
  • 15

2 Answers2

7

yield doesn't yield unless it's enumerated. In this case:

model.Pages = content.GetPages();

There is no enumeration. You could however do this:

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

You consume an iterator method by using a foreach statement or LINQ query, and unsurprisingly ToList() iterates the IEnumerable using a foreach.

Though in all honesty, I am struggling to work out what you are doing, most likely need to rethink GetPages altogether.

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
1

Your GetPages method returns an IEnumerable<T> with yield return. The compiler builds a state machine from that code.

That code will only get executed once the enumerator obtained using the GetEnumerator() method from the generated state machine will be called and iterated.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325