Explain, please, why in both for loops in the example is written && Visible , if Visible already in While ? When compiling the program I can not see the difference that with && Visible in for loops, that without.

 private void button1_Click(object sender, EventArgs e) { while (Visible) { for (int c = 0; c < 255 && Visible; c++) { this.BackColor = Color.FromArgb(c, 255 - c, c); Application.DoEvents(); System.Threading.Thread.Sleep(5); } for (int c = 254; c>=0 && Visible; c--) { this.BackColor = Color.FromArgb(c, 255-c, c); Application.DoEvents(); System.Threading.Thread.Sleep(5); } } } 
  • In your code, the Visible form property is always true . It is not needed here at all. Ah, DoEvents ! This means that during this cycle an event can occur that causes the execution of another code that can change the value of Visible to false . - Igor
  • This is an example from the book - they write there that the presence of Visible is necessary to stop the cycle when the form is closed. - Vonnengut
  • Uh, no longer the stone age. Do not use terrible DoEvents ever. Do not use nasty Thread.Sleep never. Use the divine async / await . - VladD
  • @VladD: async is needed for background tasks not related to UI, and this.BackColor = Color.FromArgb (c, 255-c, c); This is not a ride; - cpp_user
  • @cpp_user: s? I've been rolling all my life, it also captures SynchronizationContext ! Try it yourself: pastebin.com/k3HJzfV5 - VladD

1 answer 1

Seems to get it! In this example, && Visible in the for loop is necessary in order to make it possible to interrupt the for loop — as soon as Visible becomes false. Otherwise, there would be a delay due to the fact that it would not be possible to check the Visible value until the for loop is completed.