2013-05-14 2 views
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[]

+0

아니요, 코드를 다시 실행 해 보았습니다. 그것은 잘 작동하지만 증가 된 값은 전역 변수에 반영되지 않습니다. 그러나 thread.join()을 사용하면 원하는 결과를 얻을 수 있었지만 약 20 초의 시간 지연이있었습니다. –

답변

0

멀티 스레딩은 자동적으로 빠른 프로그램 실행을하지 않는 모든 글로벌 변수, 그리고 스레드가 완료 될 때까지 Thread.Join 단순히 기다립니다.

기본적으로 주 스레드가 스레드가 완료 될 때까지 계속할 수없는 경우 멀티 스레드를 사용하면 안됩니다. 멀티 스레딩이 맞지 않는 곳의

예 :

  • 여러 위치에서 여러 스레드가 한 위치에서 데이터를 기다릴 수 있도록 할 수 있습니다 정보를 다운로드하려고 각 수행 할
  • 시간이 소요 작업이 사용자 인터페이스를 응답 상태로 유지하면서

Thread.Join은 차단 작업입니다. 스레드가 wor 인 동안 사용자 인터페이스가 계속 업데이트되지 않도록합니다 왕. 이 경우 스레드가 주 스레드에게 완료를 알리도록해야합니다.

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 
    } 
} 

: 나는 당신이 여기 최선을 다하고 어떤 플랫폼,하지만 윈도우 양식에 예를 들어에 모르는

Form 클래스는 그 폼의 스레드에서 메서드를 호출 할 수 있도록하는 Invoke 방법이있다 전역 변수 및 다중 스레드 정보 : 모든 스레드가 해당 스레드에 액세스 할 수 있지만 은 일 때 스레드가 액세스합니다. 가능한 경우 여러 스레드가 액세스 할 수 없게하거나 lock 메커니즘을 사용하여 보호해야합니다.

0

많은 연구와 실험이 끝난 후. I'vs는 멀티 스레딩 부족으로 인한 문제가 아니라 데이터베이스에 너무 자주 연결되어 있음을 알게되었습니다.

내 솔루션은 데이터베이스에서 모든 데이터를 대량으로 가져 와서 루프. 이로 인해 귀중한 시간을 많이 절약 할 수있었습니다.

관련 문제