【问题标题】:Change the color of several Textbox with a delay延迟更改几个文本框的颜色
【发布时间】:2018-06-21 21:44:57
【问题描述】:

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

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

【问题讨论】:

标签: c# uwp


【解决方案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;
}

【讨论】:

    【解决方案2】:

    您的问题基本上是因为您在每个Task 之后所做的.Wait()。如果让每个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();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-05
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 2014-05-25
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多