0

我有一个函数“graph1”,它调用另一个函数,如下所示。当我打电话

graph1threader(copy, date);

我得到了我想要的答案,但这需要 30 秒以上,所以我尝试使用多线程。但是,当我使用

thread[copy] = new Thread(() => graph1threader(copy, date));//pass date,copy
thread[copy].Start();

我没有得到任何结果,即全局变量只包含 0。这是为什么呢?我该如何纠正这个问题?

void graph1()
    {

        chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
        chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

        for (int k = 0; k < 5; k++)
        {                
            int copy = k;
            DateTime date = G.AddDays(copy);
            refValues[copy] = 0;
            threshValues[copy] = 0;
            y_Values[copy] = 0;
            y__Values[copy] = 0;
            yValues[copy] = 0;

            //task[copy] = new Task(() => graph1threader(copy, date));//pass date,copy
            //ask[copy].Start();
            graph1threader(copy, date);

        }



            for (int j = 0; j < 5; j++)
            {
                DateTime temp = G.AddDays(j);
                string temper = temp.ToShortDateString();
                y__Values[j] = y__Values[j] - y_Values[j];
                xNames[j] = temper;
            }

        chart1.Series[1].Points.DataBindXY(xNames, y_Values);

        chart1.Series[2].Points.DataBindXY(xNames, y__Values);

        chart1.Series[3].Points.DataBindXY(xNames, refValues);

        chart1.Series[4].Points.DataBindXY(xNames, threshValues);

        chart1.Series[5].Points.DataBindXY(xNames, yValues);

    }

void graph1threader(int x, DateTime date)
    {
        DBConnect A = new DBConnect();
        List<string>[] list = new List<string>[4];
        list = A.mandetselect();
        int numberofmen = A.Countmandet();
        string[] man_name = list[0].ToArray();
        string[] trade = list[1].ToArray();
        string[] license = list[2].ToArray();
        string[] training = list[3].ToArray();
        string[] display_status = list[4].ToArray();
        //string abc;
        List<string>[] lista = new List<string>[5];
        List<string>[] listc = new List<string>[14];


        for (int j = 0; j < numberofmen; j++)
        {
            int flag = 0;
            if (!display_status[j].Equals("NO") && (selection == "ALL" || (selection == "LAE" && license[j] != "") || (selection == "NON LAE" && license[j] == "") || (selection == "ALL AVIONICS" && trade[j] == "Avionics") || (selection == "NON LAE AVIONICS" && trade[j] == "Avionics" && license[j] == "") || (selection == "LAE AVIONICS" && trade[j] == "Avionics" && license[j] != "") || (selection == "ALL AIRFRAMES" && trade[j] == "Airframes") || (selection == "NON LAE AIRFRAMES" && trade[j] == "Airframes" && license[j] == "") || (selection == "LAE AIRFRAMES" && trade[j] == "Airframes" && license[j] != "")))
            {
                refValues[x]++;
                threshValues[x] = 0.8 * refValues[x];
                string abc = man_name[j].Replace(" ", "_");
                int no_of_proj = A.Countproj(abc);//required
                lista = A.manprojselect(abc);//required
                string[] projname = lista[0].ToArray();
                string[] country = lista[2].ToArray();
                string[] startofproj = lista[3].ToArray();
                string[] endofproj = lista[4].ToArray();
                string Status = "";
                listc = A.Select();
                int numberc = A.Count();//number of projects, not required
                string[] nameofproj = listc[0].ToArray();
                string[] status = listc[13].ToArray();

                for (int l = 0; l < A.Countproj(abc); l++)
                {

                    for (int m = 0; m < numberc; m++)
                    {
                        if (nameofproj[m] == projname[l])
                        {
                            Status = status[m];
                        }
                    }


                    DateTime shuru = DateTime.ParseExact(startofproj[l],
                                   "dd-MM-yyyy hh:mm:ss",
                                   CultureInfo.InvariantCulture);
                    DateTime anth = DateTime.ParseExact(endofproj[l],
                                   "dd-MM-yyyy hh:mm:ss",
                                   CultureInfo.InvariantCulture);
                    if (date >= shuru && date <= anth)
                    {


                        if (Status != "PLANNED" && Status != "LO" && flag == 0)
                        {
                            y_Values[x]++;//BASIC UTILISATION
                            flag = 1;
                        }
                        if (Status == "IP" || Status == "OTD")
                            y__Values[x]++;//EXCESS
                        if (Status == "PLANNED")
                        {
                            yValues[x]++;//UNUTILISED

                        }

                    }

                }
            }
        }

    }

我最近才遇到多线程。如果代码看起来不太好,请原谅。 threshValue[], refValues[], y_Values[], y__Values[],yValues[]都是全局变量

4

2 回答 2

0

多线程不会自动使您的程序运行得更快,而Thread.Join只是等待线程完成。

基本上,如果您的主线程在线程完成之前无法继续,则不应使用多线程。

Examples of where multithreading does fit:

  • when trying to download information from several locations, you can let multiple threads wait for data from one location each
  • when you want to perform a time-consuming task while keeping the user interface responsive

The second example may be the case here, but Thread.Join is a blocking operation: it still stops the user interface from being updated while the thread is working. In that case, you'd have to let the thread inform the main thread of its completion.

I don't know on what platform you're working here, but for instance on windows forms, the Form class has an Invoke method which lets you call a method on that form's thread:

class TheForm
{
    // the method running in a separate thread
    void myThread()
    {
        // do the time consuming work
        byte[] myData = ProcessData();

        // send data to the main thread 
        Invoke(new Action<byte[]>(ThreadCompleted), myData);
    }

    // will be executed in the main thread
    void ThreadCompleted(byte[] data)
    {
        // process the data
    }
}

About global variables and multithreading: any thread can access them, but there's no telling which thread accesses them when. If you can, you should avoid letting multiple threads access them, or use a lock mechanism to protect them.

于 2013-05-14T08:45:35.473 回答
0

After much study and experimentation. I'vs learnt that the problem was not due to lack of multithreading, but rather connecting too often to the database (within my loops.)

My solution was to get all the data in bulk from the database before going into my loops. This saved a lot of precious time.

于 2013-05-17T01:10:38.757 回答