Unsubscribe / subscription Events are dangerous?

This question originally led me here: Disable TextChanged event firing

I wondered if jtmach's answer is "clean":

private void mytextbox_LostFocus(object sender, RoutedEventArgs e) { this.mytextbox.TextChanged -= this.myTextBox_TextChanged; if(textbox.Text.ToString().Contains('.')) { textbox.Foreground = new SolidColorBrush(Colors.Gray); textbox.Background = new SolidColorBrush(Colors.White); } this.mytextbox.TextChanged += this.myTextBox_TextChanged; } 

Can I unsubscribe from TextChanged -events in another event like this?

Or is it error prone because during a LostFocus, a TextChanged event could have been triggered (either by the user or by the program)?

+4
source share
1 answer

If this were in a multi-threaded context, that would be a problem. It is possible that the TextChanged event will be TextChanged at the moment when you cancel your subscription, thereby not allowing you to assume that it is working while this code is also working.

However, in this case both methods will always be executed in the user interface thread, therefore, although this code will not really be β€œbroken” (you could not fire the event with the changed text at the same time, since the user interface thread can only run one at a time from two events), but it also does not serve the purpose and can simply be deleted (because the event cannot be fired while this event handler is fired, because it blocks the user interface thread).

+2
source

Source: https://habr.com/ru/post/1488333/


All Articles