C# Async与Await用法

本文展示了一个使用C#实现的异步方法调用实例,通过多个任务并行执行,演示了如何利用异步编程提高程序效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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 CloudLearning.UI
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             AsyncPrintHelloWorld();
15             Console.ReadLine();
16         }
17 
18         public async static void AsyncPrintHelloWorld()
19         {
20             Console.WriteLine("异步方法调用开始");  
21             var result1 = TMothd1();
22             var result2 = TMothd2();
23             var result3 = TMothd3();
24             Console.WriteLine("异步方法完成");
25             int r1 = await result1;
26             int r2= await result2;
27             int r3 = await result3;
28             Console.WriteLine("{0},{1},{2}", r1, r2, r3);
29         }
30 
31         public async static Task<int> TMothd1()
32         {
33             return await Task.Factory.StartNew(() =>
34             {
35                 Thread.Sleep(5 * 1000);
36                 Console.WriteLine("TMothd1 完成");
37                 return 1;
38             });
39         }
40 
41         public async static Task<int> TMothd2()
42         {
43             return await Task.Factory.StartNew(() =>
44             {
45                 Thread.Sleep(10 * 1000);
46                 Console.WriteLine("TMothd2 完成");
47                 return 2;
48             });
49         }
50         public async static Task<int> TMothd3()
51         {
52             return await Task.Factory.StartNew(() =>
53             {
54                 Thread.Sleep(15 * 1000);
55                 Console.WriteLine("TMothd3 完成");
56                 return 3;
57             });
58         }
59 
60     }
61 }
View Code

 

转载于:https://www.cnblogs.com/tangxiaojun/p/4978129.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值