如何在单独的线程中初始化类

时间:2014-03-13 12:41:54

标签: c# asp.net multithreading

我有一个类storedetails,它从数据库中获取不同的值。从数据库中获取这些值并进行计算需要很长时间(由于一个商店的76个不同查询的数据库设计不佳)。

我生成报告的实现如下。

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; 

我的类实现是超过2000行代码

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

//time taking implementation
}
}

类的初始化是否可能出现在不同的线程中,所以我可以获得一些速度?

2 个答案:

答案 0 :(得分:0)

您是否检查过.NET 4.0中的任务并行库 - 它们简化了很多线程。

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

答案 1 :(得分:0)

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