ICommand异常,线程无法访问对象

本文关键字:访问 对象 线程 异常 ICommand | 更新日期: 2023-09-27 18:21:34

当网络connected i在Gpfgateway类中引发事件以通知网络当我在乞求工作后我断开或连接网络抛出例外Gpfgateway中的事件处理程序是Thread。

例外:

windowsBase.dll中的System.InvalidoperationException附加信息:调用线程无法访问此,因为不同线程拥有它。

参考这行代码:

 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());
    }
}

任何关于我可以做些什么来使用该线程中的对象的建议都是非常有用的。

ICommand异常,线程无法访问对象

崩溃的原因可能是网络事件没有发生在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()); } 
      );
   }
}

问候