以下为我所制作的一段代码,我的本意是将三个数字循环在textbox中不断跳动,在按下停止后三个数字停止跳动。但我尝试了多种方法,无论在何处加入break,return,abort等,始终做不到让数字停止跳动。原因出在我使用的while循环是一个死循环,但我已经找不到在满足功能前提下解决方法。希望能帮帮我在不改变功能的前提下添加一个能结束循环的办法。
接下来放上源码。
using System;
using System.Threading;
using System.Windows.Forms;
namespace 老虎机_窗体
{
- public partial class Form1 : Form
- {
-
-
- public Form1()
- {
- CheckForIllegalCrossThreadCalls = false;
- InitializeComponent();
- }
- Thread th = null;
-
- bool b = false;
-
- private void Form1_Load(object sender, EventArgs e)
- {
-
- }
-
-
-
-
-
- private void buttonStart_Click_1(object sender, EventArgs e)
- {
-
- if (th == null)
- {
- if (!this.buttonStop.Focused)
- {
- th = new Thread(lhj);
- th.IsBackground = true;//设置为后台线程
- th.Start(); //子线程开始执行方法
- }
-
- }
- }
-
- private void buttonStop_Click(object sender, EventArgs e)
- {
- //当按下此按键时,需要线程终止
-
-
-
- }
-
-
- private void lhj()
- {
- Random rnd = new Random();
- //CancellationTokenSource cts = new CancellationTokenSource();
-
-
-
-
- Thread t1 = new Thread(() =>
- {
-
- while (!this.buttonStop.Focused) //循环在textbox输出1-9
- {
-
- Thread.Sleep(1);
- this.textBox1.Text = rnd.Next(0, 9).ToString();
-
- }
-
-
-
-
- });
- t1.Start();
-
- Thread t2 = new Thread(() =>
- {
- while (!this.buttonStop.Focused)
- {
-
- Thread.Sleep(3);
- this.textBox2.Text = rnd.Next(0, 9).ToString();
-
- }
-
- });
- t2.Start();
-
- Thread t3 = new Thread(() =>
- {
- while (!this.buttonStop.Focused)
- {
- Thread.Sleep(5);
- this.textBox3.Text = rnd.Next(0, 9).ToString();
-
- }
- });
- t3.Start();
- }
-
-
-
-
- }
}
这个功能就类似于老虎机。
下图为我的窗体界面。