async和await把异步编程从回调模式变成了顺序模式,更加简洁
public virtual async Task<bool> LogParticipate(string prizeName) { Task<bool> t = Task.Run(() => { Dictionary<string, string> dicPara = new Dictionary<string, string>(); dicPara.Add("prizeName", prizeName); return MailHelper.Send(_cicid, "Ten Years-Lucky Roulette", dicPara, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "EmailTemplate"), "Roulette.html"); }); return await t; }
以上await是挂起主线程,等待Task完成。Async则是异步方法的标识。
Await等同于t.GetAwaiter().GetResult();若不想挂起主线程,可以使用t.GetAwaiter().OnCompleted(() => { });
public async void DoRoulette() { var prize = GeneratePrize(); Task<bool> t = LogParticipate(prize.Item1); GetWinningRate(); //可执行回调内容 bool result = await t; }
Await和async并不会开启新的线程,依然是Task.Run或者Factory.StartNew开启的。
时间: 2024-11-10 03:51:17