2015-11-12 54 views
0

我使用這個類來啓用和禁用一個按鈕,當網絡是 連接我在Gpfgateway類中引發一個事件來通知網絡連接並且該按鈕將被禁用,當我在斷開連接或連接網絡後發起 異常後,在 開始應用程序請求工作。 Gpfgateway中的事件處理程序是Thread。ICommand異常,線程無法訪問對象

例外:

System.InvalidoperationException在WindowsBase.dll 附加信息:因爲 不同的線程擁有它調用線程不能訪問此。

指這行代碼:

CanExecuteChanged(this, new EventArgs()) 

代碼:

public class NewAnalysisCommand : ICommand 
{ 
    private AnalysisViewModel analysisViewModel = null; 
    private Measurement measurement; 


    public NewAnalysisCommand(AnalysisViewModel viewAnalysis) 
    { 
     analysisViewModel = viewAnalysis; 
     GpfGateway.GetInstance().SystemStatus += updateCanExecuteChanged; 
    } 

    /// <summary>Notifies command to update CanExecute property.</summary> 
    private void updateCanExecuteChanged(object sender, EventArgs e) 
    { 
     CanExecuteChanged(this, new EventArgs()); 
    } 
    bool ICommand.CanExecute(object parameter) 
    { 
     return GpfGateway.GetInstance().IsConnected; 
    } 

    public event EventHandler CanExecuteChanged; 
    void ICommand.Execute(object parameter) 
    { 
     NewAnalysisViewModel newAnalysisViewModel = new NewAnalysisViewModel(); 
     newAnalysisViewModel.NavigationResolver = analysisViewModel.NavigationResolver; 

     // set CurrentPosition to -1 so that none is selected. 
     analysisViewModel.Measurements.MoveCurrentToPosition(-1); 
     analysisViewModel.Measurements.Refresh(); 
     if(((List<MeasurementViewModel>)(analysisViewModel.Measurements.SourceCollection)).Count == 0) 
     { 
      CanExecuteChanged(this, new EventArgs()); 
     } 
     analysisViewModel.NavigationResolver.GoToAnalysisSettings(newAnalysisViewModel); 

    } 

    /// <summary>Notifies command to update CanExecute property.</summary> 
    private void updateCanExecuteChanged(object sender, NotifyCollectionChangedEventArgs e) 
    { 
     CanExecuteChanged(this, new EventArgs()); 
    } 
} 

任何建議,我能做些什麼來使用從該線程對象是非常有用的。

回答

0

崩潰的原因很可能是因爲網絡事件不會在GUI線程上發生。
調用CanExecuteChanged用於修改作爲GUI對象的按鈕。
但GUI對象只能在GUI線程上修改。

速戰速決:

public class NewAnalysisCommand : ICommand 
{ 
    // ... 
    private Dispatcher dispatcher; 
    public NewAnalysisCommand() 
    { 
     // The command captures the dispatcher of the GUI Thread 
     dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher; 
    } 
    private void updateCanExecuteChanged(object sender, NotifyCollectionChangedEventArgs e) 
    { 
     // With a little help of the disptacher, let's go back to the gui thread. 
     dispatcher.Invoke(() => { 
      CanExecuteChanged(this, new EventArgs()); } 
    ); 
    } 
} 

問候