以不同时间间隔显示信息的文本框。

时间:2014-05-14 16:49:04

标签: c# winforms

我创建了动态计时器。这需要不同的时间间隔。但所有信息都出现了一次。我希望每一条信息都会在时间结束后出现。

我该怎么做?

   private void btnTest_Click(object sender, EventArgs e)
    {
        for (int x = 0; x <= 5; x++)
        {
            System.Timers.Timer timer = new System.Timers.Timer();

            timer.AutoReset=true;

            timer.Start();
            timer.Interval = ((x + 1) * 100);
            this.txtOutput.Text += "\r\r\n" + "  this out put equal to " + ((x + 1) * 100);
            Thread.Sleep((x + 1) * 100);

           this.txtOutput.Text += "\r\r\n" + "  Ends x " + x;



        }
    }

3 个答案:

答案 0 :(得分:0)

首先,你必须在UI线程之外执行此操作,文本在返回btnTest_Click方法后显示,并且在Thread.Sleep((x + 1) * 100);运行时,UI线程被冻结。

一种方法是使用BackgroundWorker,它将在另一个线程中运行DoWork事件中的代码。

但是,您必须要小心,UI控件只能从UI线程访问,因此您必须使用Form的BeginInvoke方法。更多信息in this thread

使用BackgroundWorker:

private void btnTest_Click(object sender, EventArgs e)
    {
        BackgroundWorker bw = new BackgroundWorker();
        bw.DoWork += bw_DoWork;

        bw.RunWorkerAsync();
    }

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int x = 0; x <= 5; x++)
        {
            System.Timers.Timer timer = new System.Timers.Timer();

            timer.AutoReset = true;

            timer.Start();
            timer.Interval = ((x + 1) * 100);

            this.BeginInvoke(new MethodInvoker(delegate
            {
                this.txtOutput.Text += "\r\r\n" + "  this out put equal to " + ((x + 1) * 100);
            }));

            Thread.Sleep((x + 1) * 100);

            this.BeginInvoke(new MethodInvoker(delegate
            {
                this.txtOutput.Text += "\r\r\n" + "  Ends x " + x;
            }));
        }
    }

答案 1 :(得分:0)

我认为你使用了错误的计时器。请尝试使用System.Windows.Forms.Timer,并使用实际的tick事件来执行您的逻辑:

var timer = new System.Windows.Forms.Timer();
int track = 0;
timer.Tick += (timerObject, timerArgs) => {
  timer.Interval = ((track + 1) * 100);
  this.txtOutput.Text += "\r\r\n" + " this out put equal to "
                                  + ((track + 1) * 100);
  ++track;
  if (track > 4) {
    timer.Stop();
    timer.Dispose();
    this.txtOutput.Text += "\r\r\n" + "  Ends x " + track.ToString();
  }
};
timer.Start();

答案 2 :(得分:-1)

在Windows窗体中,您可以这样做

for (var x = 0; x <= 5; x++)
{
    textBox1.Text += "\r\r\n" + "  this out put equal to " + ((x + 1) * 100);
    textBox1.Text += "\r\r\n" + "  Ends x " + x;
    Application.DoEvents();
    Thread.Sleep(200);
}