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 }
  • 相关阅读:
    Android 中Base64的操作
    android 异步图片处理 工具类
    android 跨应用跳转 启动其他应用指定界面
    C++代码案例
    Android 中 Base64的操作应用
    Python基础笔记1
    [linux] 大批量删除任务
    Python基础笔记3
    [R] 如何快速生成许多差异明显的颜色?
    Python基础笔记4
  • 原文地址:https://www.cnblogs.com/wanghaibin/p/4564930.html
Copyright © 2011-2022 走看看