Here is the scenario, I have about 50 globals, a UDP listener(which works in it's own thread) changes them when it receives new package.
Another thread(other than the main) periodically(24 times a second) reads all of those vars, and changes some UI elements.
As you might imagine, that's a pretty ungainly way of doing it. Also, I'm pretty sure, sometimes I'm having race conditions. So it's not threadsafe either.
So I decided to use events attached to properties that would fire as soon as there is a change. After some search I found this:
public class MyClass : INotifyPropertyChanged
{
private object _lock;
public int MyProperty
{
get
{
return _myProperty;
}
set
{
lock(_lock)
{
//The property changed event will get fired whenever
//the value changes. The subscriber will do work if the value is
//1. This way you can keep your business logic outside of the
setter
if(value != _myProperty)
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
}
}
}
}
private NotifyPropertyChanged(string propertyName)
{
//Raise PropertyChanged event
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class MySubscriber
{
private MyClass _myClass;
void PropertyChangedInMyClass(object sender, PropertyChangedEventArgs e)
{
switch(e.PropertyName)
{
case "MyProperty":
DoWorkOnMyProperty(_myClass.MyProperty);
break;
}
}
void DoWorkOnMyProperty(int newValue)
{
if(newValue == 1)
{
//DO WORK HERE
}
}
}
Which i got from "Daniel Sandberg". I'm pretty sure this code would do what I want. Thing is, applying that code for 50 properties don't feel like proper OOP.Shouldn't there be a easier way to raise events?
Back in the ActionScript days, this kind of event could be raised with a single line of code. C#'s event system never made much sense to me....