C# StreamReader在文本框中延迟发布

C# StreamReader在文本框中延迟发布,c#,winforms,textbox,streamreader,C#,Winforms,Textbox,Streamreader,我有这个代码来读取包含多个路径的文本文件。我想做的是将它们发布到一个文本框中,到目前为止,我的问题是我可以在streamreader要发布的每一行之间延迟1秒吗?您可以使用System.Threading类调用:Thread.Sleep(1000)每个循环迭代一次 有关System.Threading类的详细信息,请访问 编辑: 如下所述,使用Thread.Sleep会导致UI在Sleep方法期间锁定。作为替代方案,您可以尝试 下面的代码片段假设您希望通过单击按钮触发上面的代码(问题是,这是否是

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

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

有关System.Threading类的详细信息,请访问

编辑:

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

下面的代码片段假设您希望通过单击按钮触发上面的代码(问题是,这是否是实际情况还不清楚)


在这里,您只需创建一个工作线程来执行(相对)耗时的任务,而无需占用GUI。

类似的内容:

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);
   }
}
或者,正如上面评论中所建议的,也可以使用
后台工作人员

使用

实现以用户定义的间隔引发事件的计时器。此计时器针对Windows窗体应用程序进行了优化,必须在窗口中使用

2) 读取队列中的所有行

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++;
    }
});

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

Sry忘记它是windows窗体
线程。睡眠(1000)…@sab669为什么要提出一些简单的建议,导致“为什么我的UI被冻结”?我尝试了线程睡眠,但它只是说线程在该上下文中不存在,它具有基于计时器和异步/等待的解决方案。正如Alexei指出的,这将导致UI一次冻结一秒钟。如果你不想要这样的功能,我建议调查BackgroundWorker类。你不应该在UI线程上使用
Thread.Sleep
。在非UI线程上这样做需要的代码比本文中显示的要多得多dies@Ayres请参阅上面编辑的答案,包括后台工作人员信息。我稍后会尝试,还有其他工作要做。我会给你一些反馈
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++;
    }
});
Queue<string> lines = new Queue<string>( File.ReadAllLines( @"Path" ) );
private void Timer_Tick( object sender, EventArgs e )
    {
        if ( lines.Count > 0 )
        {
            richTextBox1.Text += Environment.NewLine + "Copying: " + lines.Dequeue();
            counter++;
        }
    }