Home > Back-end >  Timer Stopping on Async Button Click
Timer Stopping on Async Button Click

Time:04-08

the issue is simple my timer stops when I send a click and do something async, I don't want it to stop

The interface is pretty simple, I have 2 buttons for reading a .txt file from start to end. When button 1 pressed it needs to read using normal sync mode, this will pause the timer until it finishes, but when button 2 is pressed I excpect my timer to continue ticking and doing the reading async but when button2 is pressed it stops ticking as same in button 1 (Sync method)

Here is my code:

public Form1()
    {
        InitializeComponent();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        label1.Text = DateTime.Now.ToString("HH:mm:ss");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        textBox1.Text = " ";
        StreamReader sr = new StreamReader(@"C:\Users\alexd\Desktop\lorem.txt");
        var txt =  sr.ReadToEnd();
        textBox1.Text = txt;
    }

    private async void button2_Click(object sender, EventArgs e)
    {
        textBox1.Text = " ";
        StreamReader sr = new StreamReader(@"C:\Users\alexd\Desktop\lorem.txt");
        var txt = await sr.ReadToEndAsync();
        textBox1.Text = txt;

    }
}

CodePudding user response:

Reading the file is not freezing the UI. The problem is populating a control with a huge string will freeze the UI (and your timer) as proven by commenting out:

textBox1.Text = txt;

If you want to show large amounts of text in your form, use a RichTextBox instead of regular Textbox.

  •  Tags:  
  • c#
  • Related