Reading a text file in Threads to RichtextBox insi

2019-09-06 11:53发布

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.

3条回答
贪生不怕死
2楼-- · 2019-09-06 12:22

You can still use async/await keywords in .net 4.0. Please check http://www.nuget.org/packages/Microsoft.Bcl.Asyn

查看更多
我只想做你的唯一
3楼-- · 2019-09-06 12:25

If you are using .Net 4.5 or later, you can easily do this as follows:

protected async override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    string filename = "E:\\File\\temp.txt";
    int delayTimeMilliseconds = 5000;

    // Note: File.ReadLines() defaults to UTF8.

    foreach (string line in File.ReadLines(filename))
    {
        await Task.Delay(delayTimeMilliseconds);
        richTextBox1.AppendText(line + "\n");
    }
}

Here's a .Net 4.0 solution:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    Task.Factory.StartNew(loadTextLineByLine);
}

private void loadTextLineByLine()
{
    string filename = "E:\\File\\temp.txt";
    int delayTimeMilliseconds = 5000;

    foreach (string line in File.ReadLines(filename))
    {
        Thread.Sleep(delayTimeMilliseconds);
        string text = line; // Prevent modified closure.
        this.BeginInvoke(new Action(() => richTextBox1.AppendText(text + "\n")));
    }
}
查看更多
手持菜刀,她持情操
4楼-- · 2019-09-06 12:30

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.

查看更多
登录 后发表回答