延迟更改几个文本框的颜色

时间:2018-01-12 12:14:00

标签: c# uwp

我想以一定的延迟更改多个文本框的颜色。但是目前的代码使这成为总延迟。

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

2 个答案:

答案 0 :(得分:1)

尝试将您的方法设为async并使用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;
}

答案 1 :(得分:0)

您的问题基本上是因为您.Wait()之后的Task。如果您让每个Task运行,那就没问题了。

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