Use yield in C # for the first time,

Source: Internet
Author: User

Use yield in C # for the first time,

In the past few days, I have always seen the yield keyword in the subscription number of Python programmers. I remember that yield also exists in C #, but I only know it and I have never understood its usage, if you have time today, let's see how it works. At the beginning, I must have searched for usage. I have found two examples. One is the use of "yield" in C #, and the other is the official api yield of MSDN (C # reference)

To be honest, after reading the first example, I still had a vague concept, and I didn't understand what it was about. I didn't understand what it was like until I gave the result set in MSDN.

Let's give an example of a requirement: A method returns an IEnumerable result set (for example, returns a list <int> result). The common code is as follows:

 

 1         /// <summary> 2         ///  3         /// </summary> 4         /// <returns></returns> 5         public IEnumerable<int> Method() 6         { 7             List<int> results = new List<int>(); 8             int counter = 0; 9             int result = 1;10 11             while (counter++ < 10)12             {13                 result = result * 2;14                 results.Add(result);15             }16             return results;17         }

This completes the requirement.

But with yield, you can write it like this.

 1         /// <summary> 2         ///  3         /// </summary> 4         /// <returns></returns> 5         public IEnumerable<int> YieldDemo() 6         { 7             int counter = 0; 8             int result = 1; 9             while (counter++ < 10)10             {11                 result = result * 2;              12                 yield return result;13             }14         }

The two effects are the same, but I personally like the second one, which is more concise.

Digress: I added another knowledge point in the two examples.

The returned value IEnumerable is equivalent to IEnumerable <object>, but the results of IEnumerable must be dynamically parsed;

 

But I still cannot figure out the differences between the two implementations, so I want to see how efficient the two are when doing the same thing. Next I will try to use the while LOOP 10000000 to compare the time consumption of data retrieval.

The test results using BenchmarkDotNet are as follows:

The same is true when you use Stopwatch.

From this test, we can see that the YieldDemo method has almost no time consumption, but the actual situation is impossible, so I tried to perform a traversal test.

 

 1             Stopwatch stop = new Stopwatch(); 2             stop.Start(); 3             var res = new YieldTest().YieldDemo(); 4             foreach (var item in res) 5             { 6  7             } 8             var a = stop.ElapsedMilliseconds; 9             stop.Restart();10 11 12             var rrrrr = new YieldTest().Method();13             foreach (var item in rrrrr)14             {15 16             }17             var b = stop.ElapsedMilliseconds;18             stop.Restart();

The results of this test are a = 168, B = 142. Compared with the previous test results, I became more confused and started to break the breakpoint to see how the execution sequence is.

The result is as follows:

The YieldDemo method is not included in the breakpoint of the third line. Instead, the YieldDemo method is started only when the foreach traverses the result, what's more strange is that each foreach will go to the YieldDemo while retrieving data.

This result makes me a little confused. I can only take a closer look at the document parsing,

When the iterator method runs to the yield return statement, an expression is returned and the current position in the Code is retained. The next time you call the iterator function, it will start execution again from this position. You can use the yield break statement to terminate the iteration.

It seems that this involves the iterator. Find the knowledge point of the iterator and see this explanation in the C # iterator.

It should be emphasized that, for iterative blocks, although the methods we write seem to be executed in sequence, we actually let the compiler create a state machine for us. This is the part of the code we wrote in C #1-the caller only needs to return one value each call. Therefore, we need to remember the position in the set when the last return value is returned.

When the compiler encounters an iteration block, it creates an internal class that implements the state machine. This class remembers the exact current position of our iterator and local variables, including parameters.

This sentence seems to have resolved the above questions, but it seems a bit cloudified and takes time to digest the specific principles.

Note the restrictions on yield.

1. The yield return statement cannot be placed in a try-catch Block. You can place the yield return Statement in the try block of the try-finally statement. 2. You can place the yield break statement in a try block or catch block, but not in a finally block. 3. If the foreach subject (outside the iterator method) causes an exception, the finally block in the iterator method will be executed. 4. Anonymous method. For more information, see anonymous methods. 5. contains insecure blocks. For more information, see unsafe.

 

For the first point, I feel that there are limits on good use. Why can't I use it in try-catch?

Other usage methods are explained in detail in MSDN, so I feel that there is nothing to say.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.