Monitoring gui sections and backend code in C #

I have an application that controls some devices. I can send a string to the device and get text from the device.

I need to make a log file (only .txt) that logs all the data sent / received by the device. This should be displayed in real time in the application.

I am currently writing logs to a rich text field and from there to a file. But I want to split the internal code (pairing with the device and creating the log file) from gui. This will make the communication interface with the device more portable.

As I thought through this process, I ran into one problem: how to update the logs in real time in my application? I can think of this: Take a timer and do a gui update on a time interval. but it is not terrible. It would be nice to have a buffer between them and update gui if the buffer was changed.

Any tips on how to do this correctly?

+4
source share
1 answer

Perhaps you could make your IObservable log and make your user interface subscribe to its changes?

Another option is to implement INotifyPropertyChanged and use PropertyChangedEventHandler to notify you of changes.

Here is a snippet of code showing you how to do this with NotifyPropertyChanged:

using System.ComponentModel; public class YourClass : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } protected void AddLogLine(String log) { // do your process NotifyPropertyChanged("Log"); } } 

To register for changes, you simply do something like (in your user interface constructor):

 YourClassInstance.PropertyChanged += new PropertyChangedEventHandler(MyFunctionToHandleLogChanges); 

Note: make sure that you correctly removed and added the handler again if you changed your ClassInstance class

And then update your user interface in your interface class:

 void MyFunctionToHandleLogChanges(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Log") { // Update UI } } 
+3
source

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


All Articles