2010-02-26 121 views
1

我有一個在視圖(窗口)中聲明的委託函數。C#線程調度程序

委託函數在其他類中執行。但是當我運行的應用程序,我委託函數被調用我得到以下錯誤:

Exception types: System.invalidoperationException

Exception sources: WindowBase

Exception stack traces: System.Windows.threading.dispatcher.VerifyAcess() System.Windows.Threading.DispatcherObject.VerifyAccess() System.windows.Media.visual.verifyAPIReadWrite() ....

回答

2

這意味着,在一個線程中運行的函數訪問DispatcherObject的「擁有」一個不同的線程。 DispatcherObjects(包括DependencyObjects,如Visuals)只能從創建它們的線程訪問。所以我猜你是在不同的線程上運行你的委託,例如通過線程池或BackgroundWorker。

解決方案是在訪問Visual的屬性或方法時使用Dispacther.Invoke或BeginInvoke。例如:

private void ThreadMethod() 
{ 
    // ...this is running on a thread other than the UI thread... 
    _myVisual.Dispatcher.Invoke(DoSomethingWithMyVisual); 
} 

private void DoSomethingWithMyVisual() 
{ 
    // because it has been called via Invoke, this will run on the UI thread 
    _myVisual.PartyOn(); 
} 
+1

或者更簡潔地: _MyVisual.Dispatcher.BeginInvoke(新的行動(()=> _MyVisual.PartyOn())); – 2010-02-26 07:30:45