2011-11-19 4 views
0

이 코드가 작동하지 않는 이유는 무엇입니까? 정확한 방법을 보여주십시오.# 4의 Parallel.ForEach

private void BtnStartClick(object sender, EventArgs e) 
    { 
     var files = Directory.GetFiles(@"D:\pic", "*.png"); 
     const string newDir = @"D:\pic\NewDir"; 
     Directory.CreateDirectory(newDir); 
     Parallel.ForEach(files, currentFile => 
            { 
             string filename = Path.GetFileName(currentFile); 
             var bitmap = new Bitmap(currentFile); 
             bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone); 
             if (filename == null) return; 
             bitmap.Save(Path.Combine(newDir, filename)); 
             AddItemToListBox(string.Format("Processing {0} ", filename)); 
            } 
      ); 
    } 

    private void AddItemToListBox(string item) 
    { 
     if (listBox1.InvokeRequired) 
     { 
      listBox1.Invoke(new StringDelegate(AddItemToListBox), item); 
     } 
     else 
     { 
      listBox1.Items.Add(item); 
     } 
    } 
+1

이 무엇을 생각합니까? 예상 한 행동이 뭐니? – Polynomial

+0

Invoke에 문제가있는 것 같습니다. [호출 문제로 foreach를 병렬화] (http://stackoverflow.com/questions/3467816/problem-with-invoke-to-parallelize-foreach)에서 해결책을 찾으십시오. – Vitaliy

답변

2

Invoke에 문제가있는 것 같습니다. 당신이 작업에 Parallel.ForEach을 포장 할 필요가 UI 스레드를 차단하지 않도록하기 위해 Problem with Invoke to parallelize foreach

에서 해결책을 시도해보십시오

private TaskScheduler ui; 

private void BtnStartClick(object sender, EventArgs e) 
{ 
    ui = TaskScheduler.FromCurrentSynchronizationContext(); 

    Task.Factory.StartNew(pforeach) 
     .ContinueWith(task => 
     { 
      task.Wait(); // Ensure errors are propogated to the UI thread. 
     }, ui); 
} 

private void ForEachFunction() 
{ 
    var files = Directory.GetFiles(@"D:\pic", "*.png"); 
    const string newDir = @"D:\pic\NewDir"; 
    Directory.CreateDirectory(newDir); 
    Parallel.ForEach(files, 
     currentFile => 
     {  
      string filename = Path.GetFileName(currentFile); 
      var bitmap = new Bitmap(currentFile); 

      bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone); 
      if (filename == null) return; 

      bitmap.Save(Path.Combine(newDir, filename)); 

      Task.Factory.StartNew(
       () => AddItemToListBox(string.Format("Processing {0} ", filename)), 
       CancellationToken.None, 
       TaskCreationOptions.None, 
       ui).Wait(); 
     }); 
} 

private void AddItemToListBox(string item) 
{ 
    listBox1.Items.Add(item); 
}