In my WPF program, I need to set aircraft failure for a flight simulation software. For example, if I click "Fire Engine 1" button on MainWindow,
private DispatcherTimer DT;
private void button_Engine_1_On_Fire(object sender, RoutedEventArgs e)
{
SettingFailureCondition("Fire engine 1");
}
Then a pop-up window instance "ftc" will show up for user to set the condition to trigger the failure
private void SettingFailureCondition(string failure_name)
{
FailureTriggerCondition ftc = new FailureTriggerCondition();
...
if (ftc.ShowDialog() == true)
{
if(altitude>input)//if the altitude in the software higher than user's input
{
DT.Tick += new EventHandler((sender, e)=>MoveFailureByFlag(failure_name, flag));
DT.Interval = new TimeSpan(0, 0, 0, 1);
DT.Start();
DT.Tick -= new EventHandler((sender, e)=>MoveFailureByFlag(failure_name, flag));//Why can't this unsubscribe the event?
}
}
}
As for the above code, I need to detect if the altitude meets the requirement once per second. But once it is met, execute MoveFailureByFlag
and stop detecting it. How to do it?
if(altitude>input)//once this is met, execute function MoveFailureByFlag then stop detecting it
I am thinking about unsubscribing the event but can't find a way in this case. The following fails but I don't know why.
DT.Tick -= new EventHandler((sender, e)=>MoveFailureByFlag(failure_name, flag));//Why can't this unsubscribe the event?
Thanks for any help.
Let me answer your general question first:
DT.Tick += new EventHandler((sender, e)=>MoveFailureByFlag(failure_name, flag));
...
DT.Tick -= new EventHandler((sender, e)=>MoveFailureByFlag(failure_name, flag));//Why can't this unsubscribe the event?
These don't correspond, because they are two different event handlers (note the new
keyword).
You can, however, save your event handler in a variable and use that to unsubscribe it:
EventHandler myHandler = new EventHandler((sender, e)=>MoveFailureByFlag(failure_name, flag));
DT.Tick += myHandler;
...
DT.Tick -= myHandler;
In your specific code example, however, you will remove the event handler before the event has had time to occur, so no event will happen at all.
If you want to remove the handler after the event has occurred for the first time, you can use a "self-removing" event handler:
EventHandler myHandler;
myHandler = new EventHandler((sender, e) =>
{
MoveFailureByFlag(failure_name, flag);
DT.Tick -= myHandler;
});
DT.Tick += myHandler;
DT.Interval = ...;
DT.Start();