简体   繁体   中英

What is the best way to change from polling to events?

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

More specifically, I have a Modbus-enabled PLC and I need to make a WPF HMI for controlling it. Modbus is a communications protocol which requires polling for data changes. In contrast, WPF and .NET Framework in general promote event-driven model, so pushing data 20 times a second directly into controls seems unnatural to me. Not only does Modbus lack means of reporting data changes but also it doesn't provide high level representation of bytes, and it's up to developer to properly dissect an array of unsigned shorts into something meaningful.

While parsing such data is no big deal for me, coming up with a proper conversion to a bunch of event-enabled DependencyProperties (data binding assumed) is challenging. I wouldn't like to have a lot of initialization code or temporary storage to monitor changes.

It won't be necessary to put your cyclically polled data into dependency properties. Such data properties will only be used as source of bindings, so it would be sufficient to have them in a class that implements INotifyPropertyChanged .

I would suggest to collect data of about 10 polling cycles and update the data properties no more than two times per second. You will certainly poll in a seperate thread, so you should make sure that you invoke the PropertyChanged event on the UI thread by Dispatcher.BeginInvoke like in the code below:

public class DataCollector : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private byte[] someData;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM