.NET通过async/await实现并行
如果可以并行可以大大提高性能,但在我们的使用中,不可能全是并行的也是要有线行操作,所以我们需要在业务逻辑层进行并行操作的护展:
数据访问层不变还是以前一样如下:
public class UserDAL { public User GetUser() { User user = new User(); user.Name = "N1"; user.Address = "A1"; return user; } public List<User> GetUserList() { List<User> list = new List<User>(); list.Add(new User { Name = "N11", Address = "A11" }); list.Add(new User { Name = "N12", Address = "A12" }); return list; } }
业务逻辑层需要护展有async,如下:
public class UserBLL { UserDAL dal = new UserDAL(); public async Task<User> GetUserAsync() { return await Task.Run(() => { return dal.GetUser(); }); } public User GetUser() { return dal.GetUser(); } public async Task<List<User>> GetUserListAsync() { return await Task.Run(() => { return dal.GetUserList(); }); } public List<User> GetUserList() { return dal.GetUserList(); } }
最后是调用了,如下:
UserBLL userBLL = new UserBLL(); public async Task<ActionResult> Index() { var user = userBLL.GetUserAsync(); var listUser = userBLL.GetUserListAsync(); int t1 = Environment.TickCount; await Task.WhenAll(user, listUser); ViewBag.User = user.Result; ViewBag.ListUser = listUser.Result;
//ViewBag.User = await user;
//ViewBag.ListUser = await listUser;
ViewBag.Times = Environment.TickCount - t1; return View(); }
具体的性能我们可以测试,在数据访问层每次延时500毫秒,用并行和线行测试一下,并行大约时间在500毫秒左右,而线行则在1000毫秒左右
以上参考dudu 实际案例:在现有代码中通过async/await实现并行 http://www.cnblogs.com/dudu/p/async_await_parallel.html
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。