如何降低for循环的速度,以便可以看到颜色?

时间:2019-10-08 12:09:01

标签: c# xaml

我想延迟循环,以使其显示我放入的背景色。现在,它只是速度很快。 目的是让颜色像迪斯科一样闪烁。我使用了Thread.sleep,但是那是行不通的。

private void Disco(object sender, RoutedEventArgs e)
    {
           for (int n =0; n<=10;n++)
           {
               Background = Brushes.Coral;
               Background = Brushes.AliceBlue;
               Background = Brushes.DarkRed;
               Background = Brushes.Red;
               Background = Brushes.Blue;
               Background = Brushes.Aquamarine;
           }
       }

2 个答案:

答案 0 :(得分:1)

您可以使用{Jeren van Langen在评论中建议的async方法。

await Task.Delay(time)次更改之间使用Background将延迟给定time的更改。

private async void Disco(object sender, RoutedEventArgs e)
{
    Background = Brushes.Coral;
    await Task.Delay(500); // 500 is just an example. You can use any number in milliseconds.
    Background = Brushes.AliceBlue;
    await Task.Delay(500);
    Background = Brushes.DarkRed;
    await Task.Delay(500);
    Background = Brushes.Red;
    await Task.Delay(500);
    Background = Brushes.Blue;
    await Task.Delay(500);
    Background = Brushes.Aquamarine;
    await Task.Delay(500);
    //Set the background back to its original color here.
}

如果您需要表单继续“迪斯科”直到再次按下按钮,则可以将其包装在while循环中,该循环将一直持续到按下Button为止,或选中ToggleButton

如果您选择这条路线,建议您阅读asynchronous programming documentation。这非常有帮助。

答案 1 :(得分:-2)

此代码适用于mi,并且每5秒钟更改“后退”颜色:

    public partial class Form1 : Form
        {
            /// 
            /// a list of colors to control the sequence
            /// 

Color[] colorsList = { Color.Coral, Color.AliceBlue, Color.DarkRed, Color.Red, Color.Blue, Color.Aquamarine }; /// <summary> /// Timer to control the execution time of the color change /// </summary> System.Timers.Timer myTimer = new System.Timers.Timer(); public Form1() { InitializeComponent(); } /// <summary> /// Load or Main of class /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Load(object sender, EventArgs e) { this.BackColor = colorsList[0]; myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); myTimer.Interval = 5000; myTimer.Start(); } /// <summary> /// method that changes the color, executed by the timer /// </summary> /// <param name="source"></param> /// <param name="e"></param> private void OnTimedEvent(object source, ElapsedEventArgs e) { for (int i = 0; i < colorsList.Length; i++) { if (this.BackColor == colorsList[i]) { if (i < colorsList.Length - 1) { this.BackColor = colorsList[i + 1]; break; } else { //return to the first color this.BackColor = colorsList[0]; break; } } } } }