如何使用async / await任务设置动画按钮颜色?

时间:2015-05-23 10:48:54

标签: c# .net winforms async-await

当前版本中只有单个按钮闪烁。

主:

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

namespace NEW_Flicker_Test_Async
{
    public partial class Form1 : Form
    {
         async Task Flicker<T>(T target, TimeSpan time) where T : Control
        {
            for (var isWhite = true; ; isWhite = !isWhite)
            {
                target.BackColor = isWhite
                    ? System.Drawing.Color.White
                    : System.Drawing.Color.Black;
                await Task.Delay(time);
            }
        }

        public Form1()
        {
            InitializeComponent();

        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            await Flicker(button1, TimeSpan.FromMilliseconds(83));
            await Flicker(button2, TimeSpan.FromMilliseconds(77));
            await Flicker(button3, TimeSpan.FromMilliseconds(71));
            await Flicker(button4, TimeSpan.FromMilliseconds(66));
            await Flicker(button5, TimeSpan.FromMilliseconds(61));

        }
    }
}

1 个答案:

答案 0 :(得分:1)

using System;
using System.Threading.Tasks;
using System.Windows.Forms;

class FlickerForm
{
  public static void Execute()
  {
    var button  = new Button { Width = 200, Height = 30, Text = "Test" };
    var button2 = new Button { Width = 200, Height = 30, Top = 30, Text = "Test2" };
    var form = new Form { Width = 800, Height = 600, Controls = { button, button2 } };

    form.Load += async (_s, _e) => await Task.WhenAll
     (
      Flicker(button, TimeSpan.FromSeconds(2)),
      Flicker(button2, TimeSpan.FromSeconds(3))
     );

    Application.Run(form);
  }

  static async Task Flicker<T>(T target, TimeSpan period) where T:Control
  {
    for (var isWhite = false; ; isWhite = !isWhite)
    {
      target.BackColor = isWhite ? System.Drawing.Color.White : System.Drawing.Color.Black;
      await Task.Delay(period);
    }
  }
}