zoukankan      html  css  js  c++  java
  • C#简单易懂异步实现代码实例

    代码:来源

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Diagnostics;
     4 using System.Linq;
     5 using System.Runtime.InteropServices;
     6 using System.Text;
     7 using System.Threading;
     8 using System.Threading.Tasks;
     9 using Test_Roslyn.JSON_MODEL;
    10 
    11 namespace C_Sharp_Test
    12 {
    13     class Program
    14     {
    15 
    16         static async Task Main(string[] args)
    17         {
    18             Console.WriteLine("Main异步演示开始~~~~~");
    19             Stopwatch stopwatch = Stopwatch.StartNew();
    20             List<Task> tasks = new List<Task>
    21             {
    22             Bash(),//洗澡
    23             };
    24             tasks.Add(BreakFast());//吃早餐
    25             tasks.Add(WashClothes());//洗衣服
    26             tasks.Add(WriteArticle());//写文章
    27             tasks.Add(WritingCode());//写代码
    28             await Task.WhenAll(tasks);
    29             Console.WriteLine("Main异步演示结束~~~~~共用时{0}秒!", stopwatch.ElapsedMilliseconds / 1000);
    30             Console.ReadKey();
    31         }
    32 
    33         private static async Task Bash()
    34         {
    35             Console.WriteLine("洗澡开始~~~~~");
    36             await Task.Delay(1 * 1000);//模拟过程
    37             Console.WriteLine("洗澡结束~~~~~");
    38         }
    39 
    40         private static async Task BreakFast()
    41         {
    42             Console.WriteLine("吃早餐开始~~~~~");
    43             await Task.Delay(1 * 1000);//模拟过程
    44             Console.WriteLine("吃早餐结束~~~~~");
    45         }
    46 
    47         private static async Task WashClothes()
    48         {
    49             Console.WriteLine("洗衣服开始~~~~~");
    50             await Task.Delay(6 * 1000);//模拟过程
    51             Console.WriteLine("洗衣服结束~~~~~");
    52 
    53         }
    54 
    55         private static async Task WriteArticle()
    56         {
    57             Console.WriteLine("写文章开始~~~~~");
    58             await Task.Delay(20 * 1000);//模拟过程
    59             Console.WriteLine("写文章结束~~~~~");
    60         }
    61 
    62         private static async Task WritingCode()
    63         {
    64             Console.WriteLine("写代码开始~~~~~");
    65             await Task.Delay(12 * 1000);//模拟过程
    66             Console.WriteLine("写代码结束~~~~~");
    67         }
    68     }
    69 }

    实例:

  • 相关阅读:
    [2019南昌邀请赛网络赛D][dp]
    [ Educational Codeforces Round 65 (Rated for Div. 2)][二分]
    [hdoj5927][dfs]
    [cf1140D. Minimum Triangulation][dp]
    [hdoj6483][莫队+线段树/ST]
    使用GAC加速 解决CSP问题 Kakuro
    UVA 11427 Expect the Expected
    UVA 11021 Tribles
    UVA 11174 Stand in a Line 树上计数
    《算法概论》第八章的一些课后题目 关于NP-Complete Problem
  • 原文地址:https://www.cnblogs.com/smartisn/p/15107940.html
Copyright © 2011-2022 走看看