簡單的一個小程序,代碼如下:
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 exe_thread1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
//號碼字符串
string[] str = { "15131254154", "15251247858", "15651244567",
"15344547254", "1551247732", "15661242345",
"15461237356", "15761247611", "15873457954",
"15571247357", "15071247430", "15571678004",
"15611247553" };
//隨機產生號碼
Random r = new Random();
//記錄字符串下標
int i;
//定義線程
Thread myThread;
//線程方法
private void Thread()
{
while (true)
{
this.SetText();
}
}
private void button1_Click(object sender, EventArgs e)
{
//實例化線程
myThread = new Thread(new ThreadStart (this.Thread));
//開始線程
myThread.Start();
}
//定義委托
delegate void SetTextCallback();
//委托的方法
private void SetText()
{
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { });
}
else
{
i = r.Next(str.Length );
this.textBox1.Text =str [i ] ;
}
}
private void button2_Click(object sender, EventArgs e)
{
//結束線程
myThread.Abort();
MessageBox.Show("恭喜您得獎了!");
}
}
}