In the development, such as a large number of data acquisition, not only slow, but also affect efficiency, the following is to introduce the use of multithreading to obtain database data:
1. First create a new method to get a list of entities, such as to get the number or other types, you need to write another method, here is simply a brief introduction:
/// <summary>///returns an entity collection based on the SQL statement, which cannot be returned IQueryable, otherwise the context object is not available in the thread/// </summary>/// <typeparam name= "T" ></typeparam>/// <param name= "SQL" ></param>/// <returns></returns> Public StaticList<t> getmodellist<t> (stringSQL) { using(Roomsentities rooms =Newroomsentities ()) { returnRooms. Database.sqlquery<t>(SQL). ToList (); }}
2. Multithreaded execution Process:
//Start TimingStopwatch SW =NewStopwatch (); SW. Start ();stringSqlmember ="";stringSqlroom =""; List<Member> memberlist =NULL; List<Room> roomlist =NULL;using(Roomsentities rooms =Newroomsentities ()) { varQuerymember = rooms. Member.where (U = u.isstop = =false); Sqlmember= Querymember.tostring ();//here, ToString () takes the SQL statement varQueryroom = rooms. Room.take (Ten); Sqlroom=queryroom.tostring ();}//Open two thread executionTask T1 = Task.Factory.StartNew (() ={memberlist= getmodellist<member>(Sqlmember);}); Task T2= Task.Factory.StartNew (() ={roomlist= getmodellist<room>(sqlroom);}); Task.waitall (t1, T2); //wait for two threads to complete, waiting for the t1,t2 thread to be executed at the same timeSW. Stop (); TimeSpan ts2=SW. Elapsed; Console.WriteLine ("Run Time:"+ts2. TotalMilliseconds); Console.readkey ();
Multithreading for database data