zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
  • 相关阅读:
    [CF600E]Lomsat gelral
    [BZOJ3237]连通图
    [CF580D]Kefa and Dishes
    [BZOJ4726]Sabota?
    bzoj2120&&2453 -- 带修改莫队
    bzoj4726 [ POI2017 ] -- 树形DP
    bzoj2809 [ APIO2012 ] -- 主席树
    bzoj4216 -- 分块
    bzoj4173 -- 欧拉函数
    bzoj2982 -- Lucas定理
  • 原文地址:https://www.cnblogs.com/sandunban/p/11741355.html
Copyright © 2011-2022 走看看