C#学习-多线程小练习
Posted Kimisme
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#学习-多线程小练习相关的知识,希望对你有一定的参考价值。
1.双色球案例
namespace _18双色球案例 { public partial class Form1 : Form { private bool IsRunning; private List<Label> lbList = new List<Label>(); public Form1() { InitializeComponent(); } /// <summary> /// 保存当前线程 /// </summary> private Thread ThreadS { get; set; } /// <summary> /// 启动线程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnStatt_Click(object sender, EventArgs e) { Thread thread = new Thread(new ThreadStart(() => { IsRunning = true; Random ran = new Random(); while (IsRunning) { foreach (Label label in lbList) { if (label.InvokeRequired) { label.Invoke(new Action<string>(s => label.Text = s), ran.Next(0, 10).ToString()); } else { label.Text = ran.Next(0, 10).ToString(); } } Thread.Sleep(200); } })); thread.IsBackground = true; thread.Start(); ThreadS = thread; } /// <summary> /// 终止线程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnStop_Click(object sender, EventArgs e) { IsRunning = false; if (ThreadS == null || !ThreadS.IsAlive) { return; } else { ThreadS.Abort(); } } /// <summary> /// 动态创建label /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Load(object sender, EventArgs e) { for (int i = 0; i < 6; i++) { Label lb = new Label(); lb.Text = i.ToString(); lb.AutoSize = true; lb.Location = new Point(50 * i + 50, 100); this.Controls.Add(lb); lbList.Add(lb); } } } }
2.
以上是关于C#学习-多线程小练习的主要内容,如果未能解决你的问题,请参考以下文章