利用多線程模擬一個電腦搖獎程序,如圖所示。在點擊【滾動號碼】,啟動線程,對后臺的電話號碼進行循環顯示;點擊【開獎】按鈕,關閉線程,此時顯示在文本框中的電話號碼即為中獎號碼
?
?
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 + "恭喜你中獎了","信息提示");
??????? }
??? }
}
?