zoukankan      html  css  js  c++  java
  • 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();
    }
    }
    }

  • 相关阅读:
    运维
    Linux学习
    .net Core使用Knife4jUI更换Swagger皮肤
    VS Code中使用live Server
    去重复保留一条数据
    sql server 索引检测
    Centos 7 .Net core后台守护进程Supervisor教程
    鼠标移动 在左边放大图片
    根据配置表将数据从A表转入B表
    JS替换或切割
  • 原文地址:https://www.cnblogs.com/researcher/p/5919527.html
Copyright © 2011-2022 走看看