标签:thread 延迟 class 代码 static list result 加载 OLE
Yield:是一个关键字,通过状态机实现,充分体现了延迟加载的特性。class Program
{
static void Main(string[] args)
{
{
IEnumerable<int> results = CommonMethod();
results = YieldMethod();
}
Console.WriteLine("*******************************");
{
IEnumerable<int> results = CommonMethod();
foreach (var item in results)
{
Console.WriteLine(item);
}
}
Console.WriteLine("*******************************");
{
IEnumerable<int> results = YieldMethod();
foreach (var item in results)
{
Console.WriteLine(item);
}
}
Console.ReadKey();
}
public static IEnumerable<int> CommonMethod()
{
List<int> results = new List<int>();
int counter = 0;
int result = 1;
while (counter++ < 10)
{
Thread.Sleep(1000);
Console.WriteLine($"获取{counter}次数据");
result = 2 * result;
results.Add(result);
}
return results;
}
public static IEnumerable<int> YieldMethod()
{
int counter = 0;
int result = 1;
while (counter++ < 10)
{
Thread.Sleep(1000);
Console.WriteLine($"获取{counter}次数据");
result = 2 * result;
yield return result;
}
}
}
标签:thread 延迟 class 代码 static list result 加载 OLE
原文地址:http://blog.51cto.com/3544640/2145539