❔ 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();
}
}
}
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();
}
}
}
9 Replies
rotor_
rotor_2y ago
Ah it's because you're using Sleep which blocks the main thread @ohusq exchange Sleep(0.1); for await Task.Delay(100); And add the async modifier to the ChangeRGB method
vrijdag bierdag 🗣
Thank you, works perfectly now when do I make a function async and use await functions?
rotor_
rotor_2y ago
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 Then it picks up where it left off and finishes the method Meanwhile sleep just patiently stops what it's doing and waits
vrijdag bierdag 🗣
Ah, so it waits until a functions loop or code is done? (Which is indexed in the await)
rotor_
rotor_2y ago
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
vrijdag bierdag 🗣
Got it, thank you
rotor_
rotor_2y ago
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
vrijdag bierdag 🗣
haha, but thanks
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.