What's the best way to go from polling to events?

If you have to parse 300 bytes of raw data 20 times per second into a bunch of WPF control properties, what would be your solution?

Specifically, I have a Modbus capable PLC and I need to create a WPF control interface to control it. Modbus is a communication protocol that requires polling to change data. In contrast, WPF and the .NET Framework in general promote an event driven model, so redirecting data 20 times per second directly to controls seems unnatural to me. Not only does Modbus lack the means to represent data about data changes, but it also does not provide high-level byte representations, and the developer must correctly parse the unsigned shorts array into something meaningful.

While parsing such data is not a big deal to me, coming up with a proper transformation into a bunch of event-dependent DependencyProperties (intended data binding) is challenging. I wouldn't like to have a lot of initialization code or temporary storage to monitor changes.


source to share

1 answer

There is no need to insert polled data into dependency properties. Such data properties will only be used as a source of bindings, so it would be sufficient to have them in a class that implements INotifyPropertyChanged .

I would suggest collecting data for about 10 polling cycles and updating the data properties no more than twice a second. You will definitely be polling a separate thread, so you have to make sure you are calling the PropertyChanged event on the Dispatcher.BeginInvoke UI thread , like in the code below:

public class DataCollector : INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    private byte[] someData;

    public byte[] SomeData
        get { return someData; }
            someData = value;

            if (PropertyChanged != null)
                Application.Current.Dispatcher.BeginInvoke(PropertyChanged, this, new PropertyChangingEventArgs("SomeData"));




All Articles