Yield return usage in C #

**

Yield return effect-during return, save the state of the current function, and continue processing from the current position in the next call.

**

Advantages: When processing a loop, you can return a piece of data every time you generate a piece of data for the main function to process. In a single-threaded program, since you do not need to wait for all data to be processed before returning, you can reduce the memory footprint.
For example, if there are multiple data, if the return is processed at one time, a large amount of memory needs to be opened first, and each return requires only 1 memory unit. In a multi-threaded processing program, the processing speed of the program can also be accelerated.
A classic application is Socket. The main thread processes the data received by the Socket, while another thread is responsible for reading the contents of the Socket. When the amount of data received is relatively large, the two threads can speed up the processing speed.
Demo:

 class Program
    {
        static void Main(string[] args)
        {
            foreach (var item in GetNumbers())
                Console.WriteLine("主线程: 子线程数据 = " + item);
            Console.WriteLine("--------------------");
            foreach (var item in GetString())
                Console.WriteLine("主线程: 子线程数据 = " + item);
        }

        static IEnumerable<int> GetNumbers()
        {
            // 以[0, 1, 2] 初始化数列 list
            Console.WriteLine("初始化GetNumbers函数...");
            List<int> list = new List<int>();
            for (int i = 0; i < 3; i++)
                list.Add(i);

            // 每次 yield return 返回一个数据        
            Console.WriteLine("执行子线程...");//使用**yield 只从当前执行的位置继续执行**
            yield return list[0];
            yield return list[1];
            yield return list[2];
            Console.WriteLine("完成GetNumbers");
        }
        static IEnumerable<string> GetString()
        {
            Console.WriteLine("初始化GetString函数...");
            List<string> list = new List<string>();
            for (int i = 0; i < 3; i++)
                list.Add("子项" + (i + 1));    
            Console.WriteLine("执行子线程...");
            foreach (string str in list)//循环中使用**yield 也是只从当前执行的位置继续执行**
            {
                yield return str;
            }
            Console.WriteLine("完成GetString");
            Console.ReadLine();
        }
    }

operation result:
Insert picture description here

Published 13 original articles · praised 0 · visits 4643

Guess you like

Origin blog.csdn.net/qq_37869796/article/details/103920384