2013-03-11 66 views
0

我已經在wpf應用程序中使用BackgroundWorker的幫助來處理批量複製操作。我所說的方法DoAction像下面從工作線程工作線程沒有更新按鈕的可見性狀態

private void DoAction() 
    { 

    ..................... 
    ..................... // some code goes here and works fine 

    //Enable the Explore link to verify the package 
    BuildExplorer.Visibility = Visibility.Visible; // here enable the button to visible and gives error 
    } 

如果我在這是說的錯誤年底可見BuildExplorer按鈕知名度「因爲不同的線程擁有它調用線程不能訪問此對象。」我如何更新UI線程狀態?

回答

2

從WPF中的UI線程修改UI只是合法的。諸如改變可見性之類的操作正在修改UI並且不能從後臺工作者完成。你需要從UI線程

最常見的方式在WPF做到這一點做,這是從後臺線程捕獲值以下

  • 捕捉Dispatcher.CurrentDispatcher在UI線程
  • 呼叫Invoke做UI線程

工作例如

class TheControl { 
    Dispatcher _dispatcher = Dispatcher.CurrentDispatcher; 

    private void DoAction() { 
    _dispatcher.Invoke(() => { 
     //Enable the Explore link to verify the package 
     BuildExplorer.Visibility = Visibility.Visible; 
    }); 
    } 
} 
+0

這是確定。工作進程需要大約5到6分鐘才能完成。那麼如何在UI線程的幫助下找到完成並更新狀態? – Smaug 2013-03-11 06:35:11

+0

@RameshMuthiah:使用BackgroundWorker好友或任何線程級事件 – TalentTuner 2013-03-11 06:41:32

+0

謝謝。它幫助我 – Smaug 2013-03-11 08:34:53

0

如果您正在從不同的線程訪問,請封送控制權限。在Windows和許多其他操作系統中,控件只能由其出生的線程訪問。你不能從另一個線程中擺弄它。在WPF中,調度程序需要與UI線程相關聯,並且您只能通過調度程序對調用進行編組。

如果長時間運行的任務不是使用BackgroundWorker的類來獲取完成通知

var bc = new BackgroundWorker(); 
    // showing only completed event handling , you need to handle other events also 
     bc.RunWorkerCompleted += delegate 
            { 
             _dispatcher.Invoke(() => { 
             //Enable the Explore link to verify the package 
             BuildExplorer.Visibility = Visibility.Visible; 
            }; 
+0

感謝您的幫助 – Smaug 2013-03-11 09:02:50