user2757340
user2757340

Reputation: 3

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();
}

Upvotes: 0

Views: 482

Answers (2)

Aaron
Aaron

Reputation: 652

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();
        }
    }
}

Upvotes: 0

Jet  Chopper
Jet Chopper

Reputation: 1488

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;
}

Upvotes: 1

Related Questions