StreamReader 在文本框中延迟发布

StreamReader posting in an Textbox with delay

StreamReader file = new StreamReader(@"C:\Users\User\Documents\Files.txt");

while ((line = file.ReadLine()) != null)
{
    richTextBox1.Text += Environment.NewLine + "Copying: " + line;
    counter++;
}

我有这段代码可以读取其中包含多个路径的文本文件。我想做的是 post 它们在我到目前为止得到的文本框中,但我的问题是我可以在 streamreader 将要 post 的每一行之间延迟 1 秒吗?

您可以使用 System.Threading class 来调用:Thread.Sleep(1000); 每个循环迭代一次。

有关 System.Threading class 的更多信息,请访问 MSDN

编辑:

如下所述,使用 Thread.Sleep 会导致 UI 在 Sleep 方法期间锁定。作为替代方案,您可能想尝试 BackgroundWorker class.

以下代码段假设您希望通过单击按钮触发上面的代码(从问题中不清楚是否确实如此)。

private void startAsyncButton_Click(object sender, EventArgs e)
{
   if(backgroundWorkerA.IsBusy != true)
   {
      //start the Async Thread
      backgroundWorkerA.RunWorkerAsync();
   }
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
   StreamReader file = new StreamReader(@"C:\Users\User\Documents\Files.txt");

   while ((line = file.ReadLine()) != null)
   {
       richTextBox1.Text += Environment.NewLine + "Copying: " + line;
       counter++;
       Thread.Sleep(1000);
   }
}

在这里,您只是创建一个工作线程来完成(相对)耗时的任务,而不会占用您的 GUI。

这类东西:

System.Threading.ThreadPool.QueueUserWorkItem((obj) =>
{
    StreamReader file = new StreamReader(@"C:\Users\User\Documents\Files.txt");
    string line;
    int counter = 0;
    while ((line = file.ReadLine()) != null)
    {
        this.Invoke((Action)(() =>
            {
                richTextBox1.Text += Environment.NewLine + "Copying: " + line;
            }));
        System.Threading.Thread.Sleep(1000);
        counter++;
    }
});

或者按照上面评论中的建议,也可以使用 BackgroundWorker

Documentation

1) 使用System.Windows.Forms.Timer

实现一个定时器,它以用户定义的时间间隔引发事件。此计时器针对在 Windows Forms 应用程序中的使用进行了优化,并且必须在 window.

中使用

2) 读取队列中的所有行。

Queue<string> lines = new Queue<string>( File.ReadAllLines( @"Path" ) );

3) 使用定时器事件读取列表中的每一行。

private void Timer_Tick( object sender, EventArgs e )
    {
        if ( lines.Count > 0 )
        {
            richTextBox1.Text += Environment.NewLine + "Copying: " + lines.Dequeue();
            counter++;
        }
    }

检查是否为空 Queue.Dequeue Methodlines.Count > 0 或其他,当它变为真时停止计时器)