Home > Software engineering >  C# - Refresh WPF RichTextBox during a loop
C# - Refresh WPF RichTextBox during a loop

Time:06-21

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

CodePudding user response:

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

CodePudding user response:

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";
}

CodePudding user response:

Yes you are both right my question is not very good i'm beginner and missed to say i'm appendtext in a FlowDocument that's maybe why it rendering at the end. I also tried with New runs.

Thank you for the time you took to answer

  • Related