Reputation: 25
I use this class to enable and disable a button when the network is connected i rise an event in Gpfgateway class to notify the net is connected and the button will be disable, when i start the app at the begging work after i disconnect or connect the network throw an exception. The event handler in the Gpfgateway is Thread.
Exception:
System.InvalidoperationException in windowsBase.dll Additional info: The calling thread cannot access this because a different thread owns it.
refer to this line of code:
CanExecuteChanged(this, new EventArgs())
Code:
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());
}
}
Any suggestion what can i do to use that object from that thread is very useful.
Upvotes: 2
Views: 416
Reputation: 4913
The reason of the crash is likely because the network event doesn't happen on the GUI thread.
The call to CanExecuteChanged
goes for modification of the button that is GUI object.
But GUI objects can only be modified on the GUI thread.
A quick fix :
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()); }
);
}
}
Regards
Upvotes: 3