摇奖机-多线程

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值