using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//窗体加载
private void Form1_Load(object sender, EventArgs e)
{
InitialLabels();
}
private void InitialLabels()
{
//动态创建5个Label
for (int i = 0; i < 5; i++)
{
Label lbl = new Label();
lbl.Text = "0";
lbl.AutoSize = true;
lbl.Font = new Font("宋体", 30);
lbl.Location = new Point(60 * (i + 1), 100);
lbl.BackColor = Color.Red;
//把lbl加到窗体上和list集合中
this.Controls.Add(lbl);
listLabels.Add(lbl);
}
}
//存储那些动态创建的Label
List<Label> listLabels = new List<Label>();
//存储那些动态创建的线程对象
List<Thread> listThread = new List<Thread>();
Random rdn = new Random();
//开启摇奖功能
private void button1_Click(object sender, EventArgs e)
{
//1.启动5个线程,每个线程负责一个Lable的0-9之间的数字显示
for (int i = 0; i < 5; i++)
{
//启动每个线程
Thread t = new Thread(new ParameterizedThreadStart(lblObject =>
{
Label lbl = lblObject as Label;
if (lbl != null)
{
while (true)
{
lbl.Invoke(new Action<int>(x =>
{
lbl.Text = x.ToString();
}), rdn.Next(0, 10));
Thread.Sleep(100);
}
}
}));
listThread.Add(t);
t.IsBackground = true;
t.Start(listLabels[i]);
}
}
//停止所有线程
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < listThread.Count; i++)
{
listThread[i].Abort();
}
//清除线程
listThread.Clear();
}
}
}
摇奖机-多线程
最新推荐文章于 2021-02-19 22:56:05 发布