I have a windows Form application in which i have created a Panel.I have set the AutoScroll property of Panel True.Inside Panel i have created a RichtextBox.Now as per my requirement i have to read a text file line by line with delay in each line into this RichtextBox.I have taken timer to do this in frmHome_Load event.I have the following code to do this ..
private void frmHome_Load(object sender, EventArgs e)
{
timer1.Interval = 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
const Int32 BufferSize = 128;
using (var fileStream = File.OpenRead("E:\\File\\temp.txt"))
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
{
String line;
while ((line = streamReader.ReadLine()) != null)
{
// Process line
richTextBox1.Text += line + Environment.NewLine;
}
}
}
Now with this code as,the text file is large it is making my windows Form application hanged.Means I am not able to do any thing except closing of the window from the Task Bar.
To come out of this i thought to use Threads to read and display the texts of the textfile.With Threads i want to sleep with every 5 seconds and re starts from there. I want to know that is this way Correct and will resolve my issue.If yes How to use thread to do same with my posted Code. Please Help.
You can still use async/await keywords in .net 4.0. Please check http://www.nuget.org/packages/Microsoft.Bcl.Asyn
If you are using .Net 4.5 or later, you can easily do this as follows:
Here's a .Net 4.0 solution:
You are executing your time consuming task (the reading of txt file) in your UI thread. For this reason, your application hangs.
If you don't want that your method freezes the UI, you should schedule the execution of the method in a background thread, different from your UI thread.
To solve the issue, use a BackgroundWorker thread. Here an example.