My program displays the time in a timer event and a button
starts a function that keeps reading the content of a file until it reaches 50 lines.
The test file is created by a different process
that once in a while appends some lines to it.
How can I modify the program to avoid blocking the form during execution ?
The difference compared to WinForm Application UI Hangs during Long-Running Operation is that the functions called have to update some elements of the form.
And I don't want to use Application.DoEvents(), I have hundreds of lines of Application.DoEvents() in my programs and sometimes they create a mess.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
void Timer1Tick(object sender, EventArgs e)
{
UpdateTime();
}
void UpdateTime()
{
DateTime dt = DateTime.Now;
textBox1.Text = dt.ToString("hh:mm:ss");
}
void BtnRunClick(object sender, EventArgs e)
{
int nlines = 0;
while(nlines < 50) {
nlines = listBox1.Items.Count;
this.Invoke(new Action(() => ReadLinesFromFile()));
Thread.Sleep(1000);
}
}
void ReadLinesFromFile()
{
string sFile = @"D:\Temp1\testfile.txt";
string[] lines = File.ReadAllLines(sFile);
listBox1.Items.Clear();
foreach(string line in lines) {
listBox1.Items.Add(line);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
}
}