I have log tailing app which is executing Background worker thread in infinitive loop and checking for latest entries inside some TXT file. Once it find new entries I use Dispatcher.Invoke to update TextBox on the screen with latest entry added to the text file.
The problem is that if the source text file is being updated constantly every millisecond the user interface is just freezing since Dispatcher.Invoke is updating Textbox so often.
Wonder if there is any workaround. I could get bigger chunks from text file but don't want to spoil log tailing real-time experience, also don't want to delay writing of lines to TextBox by UI thread as this will get my application out of sync with actual data inside source text file.
Here is the Background worker DoWork method
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
reader = new StreamReader(new FileStream(file.File, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
lastMaxOffset = reader.BaseStream.Length;
while (true)
{
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
if (reader.BaseStream.Length == lastMaxOffset)
continue;
reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin);
string line = "";
while ((line = reader.ReadLine()) != null)
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
{
textLog.Text += "\r" + line;
scrollViewer.ScrollToBottom();
}));
lastMaxOffset = reader.BaseStream.Position;
}
}
as you can see UI thread is just simply append text to the TextBox and when it happen to often interface freeze