I'm currently creating an application in C# using Visual Studio. I want to create some code so that when a variable has a value of 1 then a certain piece of code is carried out. I know that I can use an if statement but the problem is that the value will be changed in an asynchronous process so technically the if statement could be ignored before the value has changed.
Is it possible to create an event handler so that when the variable value changes an event is triggered? If so, how can I do this?
It is completely possible that I could have misunderstood how an if statement works! Any help would be much appreciated.
There is no event which is raised when a given value is changed in Javascript. What you can do is provide a set of functions that wrap the specific values and generate events when they are called to modify the values. Show activity on this post.
Raising an events is a simple step. First you check the event agaist a null value to ensure that the caller has registered with the event, and then you fire the event by specifying the event by name as well as any required parameters as defined by the associated delegate. MyEvent(message);
Seems to me like you want to create a property.
public int MyProperty { get { return _myProperty; } set { _myProperty = value; if (_myProperty == 1) { // DO SOMETHING HERE } } } private int _myProperty;
This allows you to run some code any time the property value changes. You could raise an event here, if you wanted.
You can use a property setter to raise an event whenever the value of a field is going to change.
You can have your own EventHandler delegate or you can use the famous System.EventHandler delegate.
Usually there's a pattern for this:
Here's an example
private int _age; //#1 public event System.EventHandler AgeChanged; //#2 protected virtual void OnAgeChanged() { if (AgeChanged != null) AgeChanged(this,EventArgs.Empty); } public int Age { get { return _age; } set { //#3 _age=value; OnAgeChanged(); } }
The advantage of this approach is that you let any other classes that want to inherit from your class to change the behavior if necessary.
If you want to catch an event in a different thread that it's being raised you must be careful not to change the state of objects that are defined in another thread which will cause a cross thread exception to be thrown. To avoid this you can either use an Invoke method on the object that you want to change its state to make sure that the change is happening in the same thread that the event has been raised or in case that you are dealing with a Windows Form you can use a BackgourndWorker to do things in a parallel thread nice and easy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With