2011-04-06 61 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