简体   繁体   中英

How can I initialize class in a separate thread

I have a class storedetails which get different values from database. fetching these values from database and calculating takes a long time(due to poor design of the database over 76 different queries for one store).

My implementation for generating the report is as below.

string week = "32";
string year = "2013";
string[] storecode = getallstoreforweekandyear(week, year); // get all store code that were active for the week and year
ArrayList ar = new ArrayList();
foreach (string item in storecode)
{
    storedetails sd = new storedetails(item, year, week);// this initializion I want to move to another thread because it is taking time.
    ar.Add(sd);
}

ar.TrimToSize();
DataTable dt = getdtfromarraylist(ar);// convert the arraylist of class to datatable
     Gridview1.Datasourc=dt; 

My implementation of class is in over 2000 line of code

class storedetails
{
    public storedetails(string store,string year, string week)
{ 

//time taking implementation
}
}

Is it possible that initialization of classes occur in separate threads, so I can gain some speed?

Have you checked out the Task Parallel Libraries in .NET 4.0 - they simplify threading a lot.

http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx

object locker = new object();
Parallel.ForEach (storecode => item
     {
          storedetails sd = new storedetails(item, year, week);
          lock(locker)
          {
              ar.Add(sd);
          }
     });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM