2014-06-05 2 views
0

다음 코드는 C# 4.0을 사용하여 다중 스레드로 변환하려고합니다. 그렇게 할 수 있습니까? 모든 지침을 크게 주시면 감사하겠습니다.단일 스레드 C# 코드를 다중 스레드로 변환

나는 버튼 시작 프로세스를 시작해야하며 먼저 다음 몇 가지

을 멀티 스레딩 할 논리

SomeJobA(); 
SomeJobB(); 
SomeJobC(); 
... 

을 분할 다음과 같은 기능을

private void ProcessData() 
{ 
    //clear some ui text fields and disable start button and enable cancel button and set status to working 
    //open database connection 
    try 
    { 
     //populate ui multi line textbox saying that it is getting data from database 
     var dsResult = new DataSet(); 
     //populate dataset 
     //populate ui multi line textbox saying that it finished getting data from database 
     //close connection 

     if (dsResult.Tables.Count == 1 && dsResult.Tables[0].Rows.Count > 0) 
     { 
      //populate another field saying how much records we got 
      int iCount = 1; 
      foreach (DataRow dr in dsResult.Tables[0].Rows) 
      { 
       if (_stop) 
       { 
        //set the status as forced stop 
        return; 
       } 
       //populate the currently processed record count using iCount 
       //populate ui multi line textbox indicating which item that it is starting to work using dr["Item"] 
       //call some external function to process some data, inside this function i have to update ui multi line textbox as well 
       var dataFile = SearchDataFile(dr["Item"].ToString()); 
       if (dataFile == null) 
       { 
        //populate ui multi line textbox indicating that item was not found 
        iCount++; 
        continue; 
       } 
       //call another external function to process some data, inside this function i have to update ui multi line textbox as well 
       UpdateDataFile(dataFile, folderId, dr, dr["Item"].ToString()); 
       iCount++; 
      } 
     } 
     else 
     { 
      //populate ui multi line textbox indicating no data found 
     } 
     //update status saying that it is complete 
     tsslblStatus.Text = "STATUS : COMPLETE"; 
    } 
    catch (Exception ex) 
    { 
     //close connection 
     //populate ui multi line textbox indicating error occured 
     //update status to error 
    } 
    finally 
    { 
     //re adjust ui and enabling start and disable stop 
     //set _stop variable to false 
    } 
} 

감사

+0

당신은 어떤 속도 저하가 발생하는 :

당신은 당신이 병렬로 수행 할 작업을 마샬링하는 TaskFactory를 사용할 수 있습니까? 어느 부분으로 우리가 움직이기를 원합니까? – Complexity

+0

멀티 스레딩 및 GUI 응용 프로그램에주의하십시오. 멀티 스레딩은 GUI가 응답하지 않을 수 있습니다. – BossRoss

+1

@BossRoss 왜 그런가요? – Sinatr

답변

0

를 호출
start SomeJobA() thread/task 
start SomeJobB() thread/task 
start SomeJobC() thread/task 
... 
to wait or not to wait for them to finish? 

다른 스레드에서 UI를 업데이트하려면 Invoke/BeginInvoke을 사용하십시오.

+0

감사합니다. 나는 이것을 시도 할 것입니다. –

0

내가 찾은 가장 쉬운 방법은 Parallel.ForEach 방법을 사용하는 것입니다, 그래서 대신

foreach (DataRow dr in dsResult.Tables[0].Rows) 

사용

Parellel.Foreach(dsResult.Tables[0].Rows, dr => 
{ 
    //foreach body code goes here. 
}); 

그러나, 그 조작하는 알고리즘을 업데이트하려는 경우 동시성을 활용하는 UI는 나쁜 시간을 가질 것입니다. 양식 응용 프로그램을 (그리고 제대로 모르는 경우 Win 8/phone 응용 프로그램) 않습니다 UI (즉 텍스트 상자에 쓰기) 주 스레드가 아닌 다른 스레드에서 조작 할 수 있습니다.

이 알고리즘을 올바르게 병렬 처리하려면 UI를 조작하는 모든 코드를 분리해야합니다. 응용 프로그램 경우

public class MyState{ 
    public string Example {get;set;} 
} 

private MyState _state; 

private void MethodCalledFromUIThread() 
{ 
    //Update UI. 
    TextBox1.Text = string.Empty; 

    //Start parallel work in a new thread. 
    new TaskFactory().StartNew(() => ThreadedMethod()) 
     //Wait for background threads to complete 
     .Wait(); 

    //Update UI with result of processing. 
    TextBox1.Text = _state.Example; 
} 

private void ThreadedMethod() 
{ 
    //load dsResult 

    Parallel.ForEach(dsResult.Tables[0].Rows, dr => 
    { 
     //process data in parallel. 
    } 

    //Update the State object so the UI thread can get access to the data 

    _state = new MyState{Example = "Data Updated!";} 
} 
+0

감사합니다. 나는이 방법을 시도 할 것입니다. –

관련 문제