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();
}
}
}

posted @ 2016-09-29 12:49  Researcher  阅读(79)  评论(0编辑  收藏  举报