使用多线程操作
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 用多线程实现双色球
{
public partial class MainFrm : Form
{
private List<Label> lblist =
new List<Label>();
//写一个集合存储lb控件
public MainFrm()
{
InitializeComponent();
// Control.CheckForIllegalCrossThreadCalls = false;//捕获对错误线程的调用设置为false,真正项目中不要使用这种方法
}
bool isRuning =
false;
private void MainFrm_Load(
object sender, EventArgs e)
{
//循环加载6个label标签
for (
int i =
0; i <
6; i++
)
{
Label lb =
new Label();
lb.Text =
"0";
lb.AutoSize =
true;
lb.Location =
new Point(
50 * i +
50,
100);
this.Controls.Add(lb);
//将所有lb控件显示在窗体上
//写一个集合存放lb控件
lblist.Add(lb);
}
}
private void btnStart_Click(
object sender, EventArgs e)
{
isRuning =
true;
Thread thread =
new Thread(() =>
{
Random r =
new Random();
//不停改变lb的值
while (isRuning)
{
foreach (
var item
in lblist)
{
string str = r.Next(
0,
10).ToString();
if (item.InvokeRequired)
//多线程操作
{
//该属性为true,说明调用了外部线程
item.Invoke(
new Action<
string>(s => { item.Text =
s; }), str);
}
else
{
item.Text =
str;
}
}
Thread.Sleep(200);
//数字改变的太快了,因此让他200毫秒改变一次
}
});
thread.IsBackground =
true;
//设置为后台线程
thread.Start();
}
private void btnStope_Click(
object sender, EventArgs e)
{
isRuning =
false;
}
}
}
转载于:https://www.cnblogs.com/xiaoyaohan/p/9729076.html
相关资源:ASP.NET开发实战1200例(第1卷).part2