C# WinForms多线程编程-摇奖程序
利用多线程模拟一个电脑摇奖程序,如图所示。在点击【滚动号码】,启动线程,对后台的电话号码进行循环显示;点击【开奖】按钮,关闭线程,此时显示在文本框中的电话号码即为中奖号码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace Ex02_Lottery { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //定义一个泛型 List<string> liNum = new List<string>(); //定义一个全局变量 Thread thread; private void btnRoll_Click(object sender, EventArgs e) { //定义一个线程 thread = new Thread(new ThreadStart(Num)); //开启线程 thread.Start(); btnRoll.Enabled = false; } public void Num() { int i = 0; liNum.Add("13965113141"); liNum.Add("18676768761"); liNum.Add("13456468141"); liNum.Add("15456564541"); liNum.Add("13965113141"); liNum.Add("13968766141"); liNum.Add("13965113141"); liNum.Add("13123113311"); //循环 while (i < liNum.Count + 1) { if (i >= liNum.Count) i = 0; txtNum.Text = liNum[i].ToString(); i++; } } private void Form1_Load(object sender, EventArgs e) { txtNum.Enabled = false; //线程间操作无效: 从不是创建控件“ btnRoll”的线程访问它。解决方法 Form1.CheckForIllegalCrossThreadCalls = false; } private void btnLottery_Click(object sender, EventArgs e) { //挂想线程 thread.Suspend(); //恢复线程 thread.Resume(); //关闭线程 thread.Abort(); btnLottery.Enabled = false; MessageBox.Show("号码为:" + txtNum.Text + "恭喜你中奖了", "信息提示"); } } }