zoukankan      html  css  js  c++  java
  • async & await 异步编程小示例,一看就懂

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading;
     6 using System.Threading.Tasks;
     7 
     8 namespace ConAppAsync
     9 {
    10     class Program
    11     {
    12 
    13         //第一步,创建一个普通的耗时的方法
    14         static string Greeting(string name)
    15         {
    16             Thread.Sleep(3000);
    17             return String.Format("Hello, {0}", name);
    18         }
    19 
    20         //第二步,用一个异步方法包装上面的方法
    21         static Task<string> GreetingAsync(string name)
    22         {
    23             return Task.Run<string>(() =>
    24             {
    25                 return Greeting(name);
    26             });
    27         }
    28 
    29         //第三步,再创建一个能调用上面的异步方法的方法, 加关键字 async
    30 
    31         private async static void CallWithAsync()
    32         {
    33             //some other tasks
    34 
    35             string result = await GreetingAsync("王海滨");
    36 
    37             //we can add multiple "await" in same "async" method
    38             string result1 = await GreetingAsync("Ahmed");
    39             string result2 = await GreetingAsync("Every Body"); 
    40             Console.WriteLine(result+result1+result2);
    41         }
    42 
    43         static void Main(string[] args)
    44         {
    45             //最后在主入口调用上面的方法,和调用普通方法一样
    46             CallWithAsync();
    47             int length = 100;
    48             for (int i = 0; i < length; i++)
    49             {
    50                 Console.WriteLine(i);
    51             }
    52             Console.ReadKey();
    53         }
    54     }
    55 }
  • 相关阅读:
    织梦当前位置去除最后字符
    一霎清明雨,实现考勤管理。
    浅谈:C#中的非泛型集合
    简述结构和类的区别
    项目经理评分系统
    那些年我们一起~做过的魔兽系统
    浅谈:什么是.NET
    MyKTV系统项目的感想
    开发“航班查询及预定”系统
    java面试的一些问题
  • 原文地址:https://www.cnblogs.com/wanghaibin/p/4564930.html
Copyright © 2011-2022 走看看