C#基础之Async和Await 的异步编程
2024-08-30 11:56:11
官方文档地址:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/
Coffee cup = PourCoffee();
Console.WriteLine("coffee is ready");
Task<Egg> eggTask = FryEggs();
Task<Bacon> baconTask = FryBacon();
Task<Toast> toastTask = ToastBread();
Toast toast = await toastTask;
ApplyButter(toast);
ApplyJam(toast);
Console.WriteLine("toast is ready");
Juice oj = PourOJ();
Console.WriteLine("oj is ready"); Egg eggs = await eggTask;
Console.WriteLine("eggs are ready");
Bacon bacon = await baconTask;
Console.WriteLine("bacon is ready"); Console.WriteLine("Breakfast is ready!");
static async Task Main(string[] args)
{
Coffee cup = PourCoffee();
Console.WriteLine("coffee is ready");
var eggsTask = FryEggsAsync();
var baconTask = FryBaconAsync();
var toastTask = MakeToastWithButterAndJamAsync(); var eggs = await eggsTask;
Console.WriteLine("eggs are ready");
var bacon = await baconTask;
Console.WriteLine("bacon is ready");
var toast = await toastTask;
Console.WriteLine("toast is ready");
Juice oj = PourOJ();
Console.WriteLine("oj is ready"); Console.WriteLine("Breakfast is ready!"); async Task<Toast> MakeToastWithButterAndJamAsync(int number)
{
var toast = await ToastBreadAsync(number);
ApplyButter(toast);
ApplyJam(toast);
return toast;
}
}
static async Task Main(string[] args)
{
Coffee cup = PourCoffee();
Console.WriteLine("coffee is ready");
var eggsTask = FryEggsAsync();
var baconTask = FryBaconAsync();
var toastTask = MakeToastWithButterAndJamAsync(); var allTasks = new List<Task>{eggsTask, baconTask, toastTask};
while (allTasks.Any())
{
Task finished = await Task.WhenAny(allTasks);
if (finished == eggsTask)
{
Console.WriteLine("eggs are ready");
}
else if (finished == baconTask)
{
Console.WriteLine("bacon is ready");
}
else if (finished == toastTask)
{
Console.WriteLine("toast is ready");
}
allTasks.Remove(finished);
}
Juice oj = PourOJ();
Console.WriteLine("oj is ready");
Console.WriteLine("Breakfast is ready!"); async Task<Toast> MakeToastWithButterAndJamAsync(int number)
{
var toast = await ToastBreadAsync(number);
ApplyButter(toast);
ApplyJam(toast);
return toast;
}
}
最新文章
- 利用Hexo搭建个人博客-博客初始化篇
- Myeclipse8.6配置android_SDK,进行android开发(转载)
- Wow! Such Sequence!(线段树4893)
- android之TabHost(上)
- uboot环境变量初始化
- jQuery插件之artDialog
- UISlider小结
- MongoDB复制集之将现有的单节点服务器转换为复制集
- poj3249 拓扑排序+DP
- 修改Linux主机名
- 30行Python代码实现人脸检测
- django中form组件
- python中列表的常用操作增删改查
- Program.cs 累积_C#
- JS生成EXCEL(Chrome浏览器)
- 【hihoCoder 第133周】【hihoCoder 1467】2-SAT&#183;hihoCoder音乐节
- TreeView.ImageSet 属性
- mybatis使用count返回int的方法
- 【[NOI2006]最大获利】
- 2 - Bootstrap-引导类-Bootstrap/ServerBootstrap
热门文章
- XJOI夏令营501训练1——分配工作
- centos部署jeecms
- 关于obj文件的理解
- iOS开发系列-SQLite
- @Restcontroller与@controller区别
- Luogu P3007 [USACO11JAN]大陆议会The Continental Cowngress
- winDbg + VMware + window 双机联调环境搭建
- windows API 第 11 篇 GetCurrentDirectory SetCurrentDirectory
- 使用edac工具来检测服务器内存故障.
- mysql基本笔记之一