码迷,mamicode.com
首页 > 其他好文 > 详细

Yield Usage Understanding

时间:2016-09-29 13:30:31      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/researcher/p/5919527.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!