同步函数的异步化
先说下异步(Asynchronous)和多线程(Multi-threading)的区别:异步是相对与同步来说的,一般来说意味着非阻塞;异步在具体实现上是用多线程来实现的,但好处是你不用操心和管理多线程,它给你封装了一个干净的接口来调用。当然,在linux和javascript环境下,你要理解异步一般要理解事件驱动机制/Event loop: 《理解Event loop》。这里讲的主要是.NET。同步函数异步化有很多好处,但异步化是有开销的:《Understanding the Costs of Async and Await》。具体来说,下列场合适合用异步化:
- 耗时的I/O操作,例如:读文件I/O,访问网络资源网络I/O….
- 耗时的CPU的操作:建议配合多线程,例如Task.Factory启动新的线程,在线程里面进行异步访问
举例,这里有个同步方法Process(例子不太恰当,应该是耗时的I/O操作的例子比较好)
1 2 3 4 5 6 7 8 | public class Test { public int Process( int a) { System.Threading.Thread.Sleep(3000); return a + 1; } } |
现在把这个同步方法改造为异步方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | namespace ConsoleApplication6 { public class Test { public int Process( int a) { System.Threading.Thread.Sleep(3000); return a + 1; } public void ProcessAsync( int a, Action< int > callBackAction) { Func< int > func = () => { System.Threading.Thread.Sleep(3000); return a + 1; }; func.BeginInvoke((ar) => { var result = func.EndInvoke(ar); callBackAction.Invoke(result); }, null ); } } } |
测试方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication6 { class Program { static void Main( string [] args) { var tester = new Test(); Console.WriteLine( "Sync start" ); var result1 = tester.Process(1); Console.WriteLine( "Sync finish: " + result1); Console.WriteLine( "Async start" ); tester.ProcessAsync(2, (r) => { Console.WriteLine( "Async finish: " + r + " thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId); }); Console.WriteLine( "Async continue" + " thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId); Console.Read(); } } } |
输出结果:
1 2 3 4 5 6 7 | Sync start (wait 3 seconds) Sync finish: 2 Async start Async continue (wait 3 seconds) Async finish: 3 |
如果多加几个操作,看看起了几个线程:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication6 { class Program { static void Main( string [] args) { var tester = new Test(); Console.WriteLine( "Sync start" ); var result1 = tester.Process(1); Console.WriteLine( "Sync finish: " + result1); Console.WriteLine( "Async start" ); tester.ProcessAsync(2, (r) => { Console.WriteLine( "Async finish: " + r + " thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId); }); Console.WriteLine( "Async continue" + " thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId); Console.WriteLine( "Async start" ); tester.ProcessAsync(2, (r) => { Console.WriteLine( "Async finish: " + r + " thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId); }); Console.WriteLine( "Async continue" + " thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId); Console.WriteLine( "Async start" ); tester.ProcessAsync(2, (r) => { Console.WriteLine( "Async finish: " + r + " thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId); }); Console.WriteLine( "Async continue" + " thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId); Console.WriteLine( "Async start" ); tester.ProcessAsync(2, (r) => { Console.WriteLine( "Async finish: " + r + " thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId); }); Console.WriteLine( "Async continue" + " thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId); Console.Read(); } } } |
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Sync start Sync finish: 2 Async start Async continue thread id: 9 Async start Async continue thread id: 9 Async start Async continue thread id: 9 Async start Async continue thread id: 9 Async finish: 3 thread id: 13 Async finish: 3 thread id: 11 Async finish: 3 thread id: 10 Async finish: 3 thread id: 12 |
说明背后是用了多线程。
现在我们再用async和await关键字来改造一下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication6 { public class Test { public void ProcessAsync( int a, Action< int > callBackAction) { Func< int > func = () => { System.Threading.Thread.Sleep(3000); return a + 1; }; func.BeginInvoke((ar) => { var result = func.EndInvoke(ar); callBackAction.Invoke(result); }, null ); } public Task< int > TaskProcessAsync(Action< int > callBackAction) { var tcs = new TaskCompletionSource< int >(); ProcessAsync(3, (r) => { callBackAction.Invoke(r); }); return tcs.Task; } public async Task< int > QueryProcess(Action< int > callBackAction) { int i = await TaskProcessAsync(callBackAction); return i; } } public class Class1 { public async Task< int > Test() { var tester = new Test(); var i = await tester.QueryProcess((r) => { Console.WriteLine( "await Async finish: " + r + " thread id: " + System.Threading.Thread.CurrentThread.ManagedThreadId); }); return i; } } class Program { static void Main( string [] args) { var t = new Class1(); t.Test(); Console.Read(); } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述