Sunday, March 11, 2018

c# - Async method does not recognize yield return method?





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 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 GetPages(this string content)

{
var level = 0;
var value = nameof(PageModel.Page).GetDElement();
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


Answer



yield doesn't yield unless its 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.




No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...