在开发中,如大量获取数据时,不但速度慢,而且影响效率,下面就给大家介绍下用多线程获取数据库数据:
1.首先新建一个获取实体列表的方法,如想获取数量或其他类型,需要另外编写方法,这里只是做简单的介绍:
/// <summary> /// 根据SQL语句返回实体集合,这里不能返回IQueryable,否则在线程中会获取不到上下文对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <returns></returns> public static List<T> GetModelList<T>(string sql) { using (RoomsEntities rooms = new RoomsEntities()) { return rooms.Database.SqlQuery<T>(sql).ToList(); } }
2.多线程执行过程:
//开始计时 Stopwatch sw = new Stopwatch(); sw.Start(); string sqlMember = ""; string sqlRoom = ""; List<Member> MemberList = null; List<Room> RoomList = null; using (RoomsEntities rooms = new RoomsEntities()) { var queryMember = rooms.Member.Where(u => u.IsStop == false); sqlMember = queryMember.ToString(); //这里ToString()后取到的是SQL语句 var queryRoom = rooms.Room.Take(10); sqlRoom = queryRoom.ToString(); } //开启两个线程执行 Task t1 = Task.Factory.StartNew(() => { MemberList = GetModelList<Member>(sqlMember); }); Task t2 = Task.Factory.StartNew(() => { RoomList = GetModelList<Room>(sqlRoom); }); Task.WaitAll(t1, t2); //等待两个线程完成,这里等待的t1,t2线程是同时执行的 sw.Stop(); TimeSpan ts2 = sw.Elapsed; Console.WriteLine("运行时间:" + ts2.TotalMilliseconds); Console.ReadKey();