• async & await 异步编程小示例,一看就懂


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ConAppAsync
    {
        class Program
        {
    
            //第一步,创建一个普通的耗时的方法
            static string Greeting(string name)
            {
                Thread.Sleep(3000);
                return String.Format("Hello, {0}", name);
            }
    
            //第二步,用一个异步方法包装上面的方法
            static Task<string> GreetingAsync(string name)
            {
                return Task.Run<string>(() =>
                {
                    return Greeting(name);
                });
            }
    
            //第三步,再创建一个能调用上面的异步方法的方法, 加关键字 async
    
            private async static void CallWithAsync()
            {
                //some other tasks
    
                string result = await GreetingAsync("王海滨");
    
                //we can add multiple "await" in same "async" method
                string result1 = await GreetingAsync("Ahmed");
                string result2 = await GreetingAsync("Every Body"); 
                Console.WriteLine(result+result1+result2);
            }
    
            static void Main(string[] args)
            {
                //最后在主入口调用上面的方法,和调用普通方法一样
                CallWithAsync();
                int length = 100;
                for (int i = 0; i < length; i++)
                {
                    Console.WriteLine(i);
                }
                Console.ReadKey();
            }
        }
    }
  • 相关阅读:
    复制文字时自动加版权
    Linux安装Docker
    ThreadLocal 理解
    Spring多数据源动态切换
    [LOJ#500]「LibreOJ β Round」ZQC的拼图
    [JLOI2015]装备购买
    「雅礼集训 2017 Day4」洗衣服
    [BJWC2011]元素
    [51nod1577]异或凑数
    [ARC101B]Median of Medians
  • 原文地址:https://www.cnblogs.com/sandunban/p/11741355.html
Copyright © 2020-2023  润新知