![]()
using System;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 指示灯
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Task task;
CancellationTokenSource tokenSource = new CancellationTokenSource();
private void button1_Click(object sender, EventArgs e)
{
label1.Visible = true;
label1.Text = "●";//如果觉得太小调label1字体大小
if (task == null || task.IsCompleted)
{
task = new Task(new Action(run),tokenSource.Token);
task.Start();
}
}
private void button2_Click(object sender, EventArgs e)
{
tokenSource.Cancel();
label1.Visible = false;
}
private void run()
{
while (true)
{
if (label1.ForeColor == Color.Red)
{
label1.ForeColor = Color.Green;
}
else
{
label1.ForeColor = Color.Red;
}
Thread.Sleep(300);
}
}
}
}