Yield Usage Understanding

Posted Researcher

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Yield Usage Understanding相关的知识,希望对你有一定的参考价值。

When would I use Task.Yield()?

http://stackoverflow.com/questions/22645024/when-would-i-use-task-yield

 

In order to have a better understanding for above page, we need first know yield return, below is the code example, put it in a console project, and then build, run to have a look the result:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TestYieldReturn
{
class TestYield
{

/// <summary>
/// 使用 yield 的例子.
/// </summary>
/// <returns></returns>
public IEnumerable<int> GetDataListWithYield()
{
for (int i = 0; i < 5; i++)
{
// 这里模拟一个操作
// 假设 这个方法, 对于每一行数据,都要花费一段时间处理, 才能返回.
Thread.Sleep(1000);
yield return i;
}
}

 

/// <summary>
/// 不使用 yield 的例子.
/// </summary>
/// <returns></returns>
public IEnumerable<int> GetDataListWithoutYield()
{
List<int> result = new List<int>();
for (int i = 0; i < 5; i++)
{
// 这里模拟一个操作
// 假设 这个方法, 对于每一行数据,都要花费一段时间处理, 才能返回.
Thread.Sleep(1000);
result.Add(i);
}
return result;
}
}

class Program
{
static void Main(string[] args)
{
TestYield test = new TestYield();
Console.WriteLine("测试不使用 yield 的例子!");
Console.WriteLine("==开始时间:{0}", DateTime.Now);
foreach (int data in test.GetDataListWithoutYield())
{
Console.WriteLine("====处理时间:{0}, 处理结果:{1}", DateTime.Now, data);
}
Console.WriteLine("==结束时间:{0}", DateTime.Now);


Console.WriteLine();
Console.WriteLine("测试使用 yield 的例子!");
Console.WriteLine("==开始时间:{0}", DateTime.Now);
foreach (int data in test.GetDataListWithYield())
{
Console.WriteLine("====处理时间:{0}, 处理结果:{1}", DateTime.Now, data);
}
Console.WriteLine("==结束时间:{0}", DateTime.Now);

Console.ReadLine();
}
}
}

以上是关于Yield Usage Understanding的主要内容,如果未能解决你的问题,请参考以下文章

php 生成器 yield

PyTorch 101 Part 1: Understanding Graphs, Automatic Differentiation and Autograd

Understanding Convolutions

Understanding LSTM Networks

Understanding sun.misc.Unsafe

转载Understanding and using FireMonkey Layouts