C#利用线程实现抽奖系统

界面如下:
C#利用线程实现抽奖系统
1、先定义Thread类,点击按钮时调用线程的Start()方法

 private void button1_Click(object sender, EventArgs e)
        {
            if ("".Equals(textBox1.Text) && "".Equals(textBox2.Text))
            {
                MessageBox.Show("数值范围不能为空!\n仅限数字", "警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (button1.Text.Equals("开始"))
            {
                t = new Thread(Start);
                t.Start();
                Control.CheckForIllegalCrossThreadCalls=false;
                button1.Text = "停止";
            }
            else
            {
                t.Abort();
                button1.Text = "开始";
            }
        }

2、编写没有返回值的方法,定义Random类,随机生成随机数,然后调用线程的Sleep()方法,让线程阻塞就可以实现定时随机数

 private void Start()
        {
            while (true)
            {
                try
                {
                    label4.Text = Convert.ToString(rd.Next(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text)));
                    progressBar1.Value = rd.Next(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text));
                    Thread.Sleep(Convert.ToInt32(textBox3.Text));
                }
                catch (Exception ex)
                {
                }
            }
        }

注意:如果没有Control.CheckForIllegalCrossThreadCalls=false这句代码,程序会报线程异常