C#
C#

help

Root Question Message

ohusq
ohusq2/16/2023
❔ Form does not show up after using loop

My WindowsForm does not show up when using a for(;;) loop and I'm new to csharp. Any explanation??

namespace csNotes
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            ChangeRGB();
            InitializeComponent();
        }

        void Sleep(double ms)
        {
            Thread.Sleep((int)(ms * 1000));
        }

        void ChangeRGB()
        {
            for(; ;)
            {
                Sleep(0.1);
                // Change RGB
                int c1 = new Random()
                    .Next(0, 255);
                int c2 = new Random()
                    .Next(0, 255);
                int c3 = new Random()
                    .Next(0, 255);

                BackColor = Color.FromArgb(c1, c2, c3);
            };
        }
        private void ClearButton_Click(object sender, EventArgs e)
        {
            // Clear the text box
            inputBox.Clear();
        }
    }
}
Rotor
Rotor2/16/2023
Ah it's because you're using Sleep which blocks the main thread
Rotor
Rotor2/16/2023
@410452026137247744 exchange Sleep(0.1); for await Task.Delay(100);
Rotor
Rotor2/16/2023
And add the async modifier to the ChangeRGB method
ohusq
ohusq2/16/2023
Thank you, works perfectly now
ohusq
ohusq2/16/2023
when do I make a function async and use await functions?
Rotor
Rotor2/16/2023
Honestly I don't fully understand what the async keyword does to a method. From what I've heard, it tells the compiler that once the code hits the await keyword it can make a continuation (basically puts a bookmark in and closes the book) and then works on other code until whatever task is completed
Rotor
Rotor2/16/2023
Then it picks up where it left off and finishes the method
Rotor
Rotor2/16/2023
Meanwhile sleep just patiently stops what it's doing and waits
ohusq
ohusq2/16/2023
Ah, so it waits until a functions loop or code is done? (Which is indexed in the await)
Rotor
Rotor2/16/2023
Well the thing that's being awaited must always be either a Task object or an async method (which compiles to return a Task), so at a guess then C# stores a reference to that task and lets it run in the background (or shares processor time with it) while prioritising the rest of the program. Then once the task claims it's completed (or errored) then C# goes back and continues the ChangeRGB method with the completed task
ohusq
ohusq2/16/2023
Got it, thank you
Rotor
Rotor2/16/2023
So while blocking the thread would be like boiling water and staring at it until it's done, using async would be where you'd spend the time chopping vegetables haha
ohusq
ohusq2/16/2023
haha, but thanks
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy