2011-04-06 36 views
2

這是否比設置後臺工作線程效率低?因爲它運作良好,看起來更清潔。在循環中,我調用BeginInvoke 3x - 向主窗口datagrid添加行,並更新進度條和消息。這種線程在WPF/C#中效率低嗎?

public MyConstructor() 
{ 
    InitializeComponent(); 

    ThreadStart start = delegate() 
    { 
     for (...) 
     { 
      ... 
      MyWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal, 
       new Action(delegate() 
       { 
        // Do something on the MyWindow thread. 
       } 
      )); 
      ... 
     } 

     // Intensive loop now done and we close this processing window. 
     this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, 
      new Action(delegate() 
      { 
       this.Close(); 
      } 
     )); 
    }; // ThreadStart 

    new Thread(start).Start(); 
} 

回答

2

這是確定十歲上下,但有幾點:

  • 或許你也應該Thread對象上設置的IsBackground,所以它不會導致您的應用程序在退出掛起。
  • 如果這是一個短期運行的活動,那麼你不應該創建一個新的線程,而應該在.NET4上使用ThreadPool.QueueUserWorkItem或新的'Task'。
  • 如果您的後臺線程(無論是池還是手動創建)都存在未處理的異常,則應用程序將會以很小的失敗執行。像「任務」這樣的事情處理得更好。

你真的不符合「高效」的很清楚,但BackgroundWorker的一般是在做這樣的事情的一個更好的方式 - 如果不出意外,這將使用一個線程池,這比便宜得多手動創建的線程。

4

它並不完全看起來很乾淨,我...
但除此之外,我看不出有什麼理由不這樣做。但我也沒有看到一個原因,不使用BackgroundWorker:

private void BWDoWork(...) 
{ 
    for (...) 
    { 
     // ... 
     worker.ReportProgress(...); 
    } 
} 

private void BWReportProgress(...) 
{ 
    // do something on the MyWindow thread 
} 

private void BWCompleted(...) 
{ 
    this.Close(); 
} 

它看起來更清潔我的,因爲你是在線程和UI更新所做的實際工作中稍加分離.. 。

+1

+1,'BackgroundWorker'提供了一個有用和清晰的多線程功能,我看不到任何理由避免使用它 – Damascus 2011-04-06 09:09:40