.NET通過async/await實現並行

韓天偉發表於2014-12-12

如果可以並行可以大大提高效能,但在我們的使用中,不可能全是並行的也是要有線行操作,所以我們需要在業務邏輯層進行並行操作的護展:

資料訪問層不變還是以前一樣如下:

    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

相關文章