Multithreading to get Database data

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.