现在我使用的方法在连接事件被引发时一直更新,但现在连接我使用不同的线程我有问题从Icommand线程调用该事件我得到一个错误System.StackOwverflowException,我读了互联网回合这个问题和这个问题我认为凸轮解决与祈求者,但我不明白调用者的概念如何使用它。
我的代码:
public class NewMeasurementCommand : ICommand
{
private MeasurementViewModel measurementViewModel = null;
private BaseViewModel baseViewModel;
private GpfGateway gpfGateway;
public NewMeasurementCommand(MeasurementViewModel viewModel)
{
measurementViewModel = viewModel;
GpfGateway.GetInstance().SystemStatus += updateCanExecuteChanged;
}
/// <summary>Notifies command to update CanExecute property.</summary>
private void updateCanExecuteChanged(object sender, EventArgs e)
{
updateCanExecuteChanged(sender, new EventArgs());
}
bool ICommand.CanExecute(object parameter)
{
return GpfGateway.GetInstance().IsConnected;
}
public event EventHandler CanExecuteChanged;
void ICommand.Execute(object parameter)
{
NewMeasurementViewModel newMeasurementViewModel = new NewMeasurementViewModel();
measurementViewModel.MeasurementModel.MeasurementStep = new MeasurementInfoStep();
measurementViewModel.MeasurementModel.MeasurementStep.NewMeasurementVM = newMeasurementViewModel;
GpfGateway.GetInstance().ControllerValuesArrived += measurementViewModel.MeasurementModel.MeasurementStep.RemoteControllerArrived;
newMeasurementViewModel.MeasurementModel = measurementViewModel.MeasurementModel;
newMeasurementViewModel.MeasurementModel.CurrentMeasurement = new Measurement();
measurementViewModel.MeasurementModel.MeasurementStep.CurrentMeasurement = newMeasurementViewModel.MeasurementModel.CurrentMeasurement;
newMeasurementViewModel.NavigationResolver = measurementViewModel.NavigationResolver;
measurementViewModel.MeasurementModel.CurrentMeasurement = new Measurement();
measurementViewModel.MeasurementModel.MeasurementStep.CurrentMeasurement = measurementViewModel.MeasurementModel.CurrentMeasurement;
measurementViewModel.MeasurementModel.CurrentMeasurement.Tester = Environment.UserName;
measurementViewModel.NavigationResolver.GoToMeasurementInfoStep(newMeasurementViewModel);
}
private void updateCanExecuteChanged(object sender, NotifyCollectionChangedEventArgs e)
{
CanExecuteChanged(this, new EventArgs());
}
}
}
我尝试做什么:
public delegate void InvokeDelegate();
private void EnabledChanged(object sender, EventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate
{
EnabledChanged();
});
if(sender == gpfGateway.IsConnected);
}
如果有人有任何建议,那将非常有帮助。
答案 0 :(得分:2)
你的堆栈溢出是因为你的EnabledChanged函数调用了自己。所以它只是回想起来,直到它发展为止。
你会发现他们不会从本身调用函数,而是从其他地方调用函数。
你能做的就是这样的事情
private void UpdateStatus(String message)
{
if (this.InvokeRequired)
this.Invoke((MethodInvoker)delegate
{
UpdateStatus(message);
});
else
label1.Text = message;
}
虽然这是在标签上设置文字,但它仍然是一个合理的例子。任何GUI元素都无法从另一个线程中播放,因此,您可以在任何地方使用此类函数,如果需要,则调用该命令。在这种情况下,您可以让它自己调用,因为在调用它之后不需要再次调用它自己。