简体   繁体   中英

Change the color of several Textbox with a delay

I want to change the color of multiple textbox with a certain delay. But the current code makes this the total delay.

private void Button_Click(object sender, RoutedEventArgs e)
{
        System.Threading.Tasks.Task.Delay(25).Wait();
        EMS.Background = RED;
        System.Threading.Tasks.Task.Delay(50).Wait();
        XMS.Background = RED;
        System.Threading.Tasks.Task.Delay(50).Wait();
        XSMS.Background = RED;                   
        System.Threading.Tasks.Task.Delay(2000).Wait();
}

Try to make your method as async and use await Task.Delay() :

private async void Button_Click(object sender, RoutedEventArgs e)
{
    EMS.Background = RED;
    await Task.Delay(50);
    XMS.Background = RED;
    await Task.Delay(50);
    XSMS.Background = RED;
}

Your problem is basically because of the .Wait() you're doing after each Task . If you just let each Task run, it'll be fine.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Anything
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var dict = new Dictionary<TextBox, int>
            {
                [new TextBox {Top = 25}] = 250,
                [new TextBox {Top = 50}] = 500,
                [new TextBox {Top = 75}] = 750,
                [new TextBox {Top = 100}] = 2000
            };

            var form = new Form();
            var button = new Button {Text = "Click Me"};

            button.Click += (o, e) =>
            {
                foreach (var item in dict)
                {
                    Task
                        .Delay(TimeSpan.FromMilliseconds(item.Value))
                        .ContinueWith(_ => item.Key.BackColor = Color.Red);
                }
            };

            form.Controls.Add(button);
            form.Controls.AddRange(dict.Keys.OfType<Control>().ToArray());

            form.ShowDialog();

            Console.ReadKey();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM