简体   繁体   中英

C# - Refresh WPF RichTextBox during a loop

I'm new learner in C# and i have a simple problem.

I do classic loop of 15 iterations with a Threat.Sleep of 3 secondes in each ones and inside this loop at each iteration i'm addind text to my RichTextBox. BUT the text only appear at the end of the 15 iterations of 3 secondes ! :(

I want the text to be added at each iteration in the loop :) Is there a way to do that ?

Thank you for helping :)

AMIGA RULEZ

I tested this code and it worked. When i press the button, the RTB adds the word "hello" each 3 seconds.

    private async void button1_Click(object sender, EventArgs e)
    {
        for(int i=0; i<16; i++)
        {
            richTextBox1.Text += "hello";
            await Task.Delay(3000);
        }
    }

Thread.Sleep will block the current thread. When a thread is blocked it cannot do anything else. So if it is the UI thread it cannot re-render the UI until the thread is unblocked. Because of this it is recommended to never block the UI thread .

A workaround is to use Task.Delay and async/await instead. Internally this will cause your code to be rewritten to a state machine. In principle transforming it to something like the following pseudo code

int i = 0;
timer = new Timer(TimerCallback, period: 3s);
timer.Start();
...
public void TimerCallback(){
    if(i >= 16){
        timer.Stop();
        return;
    }
    richTextBox1.Text += "hello";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM