Continuously update control (listBox) from live feed (file) c#

244 views Asked by At

I'm currently doing a small app that reads a log file that is continuously updated, parses it and shows relevant information.

I started doing the prototype in a console app and everything is working smoothly. Now I'm totally stuck when trying to, instead of outputting to the console, trying to do it to a control (a listBox in this case).

The UI freezes as the read never ends even thou is an async method and works flawlessly as a console app.

I'm trying to find information but not so sure if I have to run background workers or what kind of approach should I make.

The current situation is as follows:

  • Win form with some controls
  • Class that handles the reading

The class works as I said as a console app. It reads continuously from the file and parses the information and outputs it but if instead outputting I try to add info to the listbox, the UI freezes.

Quick update:

The async method is an enclosed while(almostalwaystrue) that's always reading for new data if there is.

Hope it is clear. Any help will be appreciated.

Thanks.

1

There are 1 answers

0
Wallack On BEST ANSWER

I used a FileSystemWatcher. As the log is initially created I do a first read and then I instantiate the watcher. Whenever is a change, the watcher reads from the last point. Then I ran into a different problem.

I couldn't access the UI elements as they were instantiated in a different thread but this fixed it:

        if (this._listbox.InvokeRequired)
            this._listbox.Invoke(new MethodInvoker(delegate
            {
                this._listbox.Items.Add(newItem);

            }));
        else
            this._listbox.Items.Add(newItem);

So I have that going for me which is nice :)