2011-01-19 5 views
1

Parallel.ForEach가 제대로 작동하는 데 문제가 있습니다. 내가 richtextbox에 파일 내용 또는 mutliple 파일 내용 (각 파일은 로그 파일을 나타냅니다)로드 listview 컨트롤이 있습니다. Foreach 루프를 사용하여 모든 작업을 수행했지만 100 개 이상의 파일을로드 할 때 병렬 작업으로 인해로드 시간이 단축되는 것으로 결정했습니다.Parallel.ForEach 및 ListView 컨트롤

여기는 foreach 루프에 사용했던 코드 블록입니다. Parallel을 얻으려면 어떻게해야합니까?

//Set cursor to WaitCursor Style 
this.Cursor = Cursors.WaitCursor; 

//Clear Messages RichTexBox 
this.rtbMessages.Clear(); 

//Loop through each selected file 
foreach (ListViewItem Item in lvMessageFiles.Items) 
{ 
    //Check if item is selected in the listview 
    if (Item.Selected && rtbMessages.TextLength < rtbMessages.MaxLength) 
    { 
     //Get Path to message file 
     filename = String.Format("{0}\\Data\\Log\\{1}.log", Global.AppPath, Item.SubItems[0].Text); 

     //Set Timeline Events calendar to selected items created date 
     cvTimeline.ShowDate(Convert.ToDateTime(lvMessageFiles.SelectedItems[0].SubItems[2].Text)); 

     //Check if file exists 
     if (File.Exists(filename)) 
     { 
      //streamreader to read the file 
      reader = new StreamReader(filename); 

      //to copy the read content in to richtextbox 
      string MessageContents = String.Format("{0}\n{1}\n", ("file:///" + filename.Replace(" ", "%20").Replace("\\", "/")), reader.ReadToEnd()); 
      rtbMessages.Text += MessageContents; 

      // closing streamreader 
      reader.Close(); 
     } 
    } 

} 

//Set cursor to WaitCursor Style 
this.Cursor = Cursors.Default; 

답변

0

당신이 될 것입니다 분명 Parallel.ForEach에 스레드가 아닌 UI 스레드에서 UI를 업데이트 할 수 없습니다 있습니다. 대신 Invoke 메서드를 사용하여 을 rtbMessages으로 설정하고 cvTimeline.ShowDate

3

2 개의 작업을 수행해야합니다.

1)이 특정 코드로 허용되지 않는 백그라운드 스레드에서 UI를 수정하려고합니다.
2) 성능이 "I/O"이기 때문에이 시나리오는 병렬화를위한 좋은 후보는 아닙니다. 하나의 하드 드라이브에 "묶여"있습니다. 당신이로드 시간을 단축하려면, 여러 개의 하드 드라이브에있는 파일을 분할하고 병렬화는

Is Parallel File.Read Faster than Sequential Read?를 볼 가치가있을 수 있습니다

+0

좋은 점 ...이 모든 파일은 같은 드라이브, 심지어 폴더에있을 것입니다, 각 그것을 병렬 훨씬 이해가되지 않는 파일의 어떤 CPU를 많이 사용하는 처리가 없기 때문이다. –

+1

두 가지 모두 좋은 점입니다. 또한 Parallel.ForEach에서 순서가 보장되지 않으므로 모든 로그 파일이 다소 임의의 순서로 표시됩니다 – BrokenGlass

0

나는 어쨌든,이 블로그에서 살펴 ...이 질문에 데자뷰를 경험하고있다 조. 내 취향은 매우 간단하지만 달성하려는 작업을 정확히 수행합니다. 새로운 .NET 4 병렬 메커니즘을 사용하여 동시 콜렉션을 사용하면서 UI를 업데이트하십시오. 비록 각자의 일은 아니지만 과업.

http://blogs.msdn.com/b/csharpfaq/archive/2010/06/18/parallel-programming-task-schedulers-and-synchronization-context.aspx