首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计时器和while循环

计时器和while循环
EN

Stack Overflow用户
提问于 2016-07-23 06:06:02
回答 4查看 1.4K关注 0票数 0

我想每隔1秒读取一行并将其放入文本框中。我管理了下面的代码:

代码语言:javascript
复制
private void button1_Click(object sender, EventArgs e)
{
    while ((line = file.ReadLine()) != null)
    {
        timer.Start();
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    textBox1.text += line + "\r\n";
}

但是line是不可访问的。我也尝试了类似这样的东西:

代码语言:javascript
复制
private void button1_Click(object sender, EventArgs e)
{
    timer.Start();
}


private void timer1_Tick(object sender, EventArgs e)
{

    while ((line = file.ReadLine()) != null)
    {
        textBox1.Text += line + "\r\n";
    }

}

但它忽略了计时器间隔。更重要的是,我不知道如何在这两个示例中停止计时器。你能给我点建议吗?我能用这个做什么?

编辑

有什么想法可以解释为什么这段代码可以很好地使用if,但不适合while

代码语言:javascript
复制
 private void timer1_Tick(object sender, EventArgs e)
        {

            while ((line1 = file1.ReadLine()) != null)
            {


                while ((line2 = file2.ReadLine()) != null)
                {

                    try
                    {
                            //some code
                    }

                    catch
                    {

                            //some code
                    }

                    finally
                    {
                            //some code

                    }

                }
               


            }
          
                timer1.Stop();
            

        }

我希望将file2中的每一行与file1中的每一行组合在一起。

EN

Stack Overflow用户

发布于 2016-07-23 06:48:27

此代码将从给定文件(当前为c:\myfile\test.xml)中提取一行并将其读入数组,然后启动计时器。一旦计时器启动,它将确定是否满足您的数据结束。如果仍然有数据,那么你将把它附加到文本框中。如果没有数据留下,计时器将停止。您可以再次按下该按钮以重新启动该过程。

代码语言:javascript
复制
    //holds each line of the file contents
    string[] lines = null;
    //sets the current line number that you are at in the lines array
    int curline = 0;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //reads all lines of files and starts the timer
        lines = File.ReadAllLines(@"C:\myfile\test.xml");
        curline = 0;
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        //if not end of data then insert on another line of the textbox
        if (curline < lines.Length)
        {
            textBox1.Text += lines[curline] + "\r\n";
            curline++;
        }
        else
        {
            //else stop the timer
            timer1.Stop();
        }
    }

祝你编码愉快,Jason

票数 2
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38535908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档