zoukankan      html  css  js  c++  java
  • async await

    顺序执行

    class Program
    {
    static void Main(string[] args)
    {
    new MyClass();
    Console.Read();
    }
    }
    public class MyClass
    {
    public MyClass()
    {
    Console.WriteLine(String.Format("MyClass() Start. 时间:{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)));
    DisplayValue();  

    Console.WriteLine(String.Format("MyClass() End. 时间:{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)));
    }
    public Task<double> GetValueAsync(double num1, double num2)
    {

    return Task.Run(() =>
    {
    for (int i = 0; i < 1000000; i++)
    {
    num1 = num1 / num2;
    }
    return num1;
    });
    }
    public void DisplayValue()
    {
    double result = GetValueAsync(1234.5, 1.01).Result ;
    System.Threading.Thread.Sleep(5000);
    Console.WriteLine(String.Format("Value is : {0} 时间:{1}",result,DateTime.Now.ToString(CultureInfo.InvariantCulture)));
    }
    }

    异步执行

    class Program
    {
    static void Main(string[] args)
    {
    new MyClass();
    Console.Read();
    }
    }
    public class MyClass
    {
    public MyClass()
    {
    Console.WriteLine(String.Format("MyClass() Start. 时间:{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)));
    DisplayValue(); //这里不会阻塞

    Console.WriteLine(String.Format("MyClass() End. 时间:{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)));
    }
    public Task<double> GetValueAsync(double num1, double num2)
    {

    return Task.Run(() =>
    {
    for (int i = 0; i < 1000000; i++)
    {
    num1 = num1 / num2;
    }
    return num1;
    });
    }
    public async void DisplayValue()
    {
    double result = await GetValueAsync(1234.5, 1.01);//此处会开新线程处理GetValueAsync任务,然后方法马上返回
    //这之后的所有代码都会被封装成委托,在GetValueAsync任务完成时调用
    System.Threading.Thread.Sleep(5000);
    Console.WriteLine(String.Format("Value is : {0} 时间:{1}",result,DateTime.Now.ToString(CultureInfo.InvariantCulture)));
    }
    }

  • 相关阅读:
    LINQ Practice
    windows下python环境安装
    kafka安装教程
    使用python连接mysql/oracle
    使用百度地图实现地图网格
    单链表反转java代码
    mysql的索引问题分析
    java中String字符串的==解析
    辗转相除法的原理
    myeclipse2014新建maven项目
  • 原文地址:https://www.cnblogs.com/zhshlimi/p/5465859.html
Copyright © 2011-2022 走看看