异步委托 多线程实现摇奖器 winform版
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 _08_摇奖机
{
//创建六个invoke方法(控件调用的时候的委托,用来给lable控件赋值)
public delegate void MyDelegate1(int num);
public delegate void MyDelegate2(int num);
public delegate void MyDelegate3(int num);
public delegate void MyDelegate4(int num);
public delegate void MyDelegate5(int num);
public delegate void MyDelegate6(int num);
public partial class Form1 : Form
{
public MyDelegate1 md1;
public MyDelegate1 md2;
public MyDelegate1 md3;
public MyDelegate1 md4;
public MyDelegate1 md5;
public MyDelegate1 md6;
//此委托用来作异步委托,旨在让clr自动创建另一个线程来完成主线程要做的操作,以缓解主线程的压力
public delegate void MyDelegate(bool b);
public Form1()
{
InitializeComponent();
md1 = SetLable1;
md2 = SetLable2;
md3 = SetLable3;
md4 = SetLable4;
md5 = SetLable5;
md6 = SetLable6;
}
//用来存放子线程对象
private Thread nameThread;
private int id;
private void button1_Click(object sender, EventArgs e)
{
MyDelegate md = new MyDelegate(this.SetNumberData);;
if (button1.Text.Trim()=="开始")
{
button1.Text = "停止";
//调用异步委托,就是在另一个线程中执行此委托绑定的方法
IAsyncResult result = md.BeginInvoke(true,null, null);
}
else
{
button1.Text = "开始";
//停止的话就相当于终止子线程
nameThread.Abort();
}
//首先要想清楚 要给主线程的空间lable赋值,那么就必须是主线程干的事
//md.EndInvoke(result);
}
public void SetNumberData(bool b)
{
while (b==true)
{
List<int> listNum = new List<int>();
Random random = new Random();
//随机生成6个数
while (listNum.Count <= 6)
{
int n = random.Next(0, 10);
listNum.Add(n);
}
//不是创建此控件的线程调用此控件的时候就必须调用invoke方法
if (this.label1.InvokeRequired)
{
this.Invoke(md1, listNum[0]);
}
else
{
label1.Text = listNum[0].ToString();
}
if (this.label2.InvokeRequired)
{
this.Invoke(md2, listNum[1]);
}
else
{
label2.Text = listNum[1].ToString();
}
if (this.label3.InvokeRequired)
{
this.Invoke(md3, listNum[2]);
}
else
{
label3.Text = listNum[2].ToString();
}
if (this.label4.InvokeRequired)
{
this.Invoke(md4, listNum[3]);
}
else
{
label4.Text = listNum[3].ToString();
}
if (this.label5.InvokeRequired)
{
this.Invoke(md5, listNum[4]);
}
else
{
label5.Text = listNum[4].ToString();
}
if (this.label6.InvokeRequired)
{
this.Invoke(md6, listNum[5]);
}
else
{
label6.Text = listNum[5].ToString();
}
//记录下当前的线程对象,以便于在点击停止按钮的时候终止此线程
nameThread = Thread.CurrentThread;
Thread.Sleep(300);
}
//id=Thread.CurrentThread.ManagedThreadId;
}
public void SetLable1(int n)
{
label1.Text = n.ToString();
}
public void SetLable2(int n)
{
label2.Text = n.ToString();
}
public void SetLable3(int n)
{
label3.Text = n.ToString();
}
public void SetLable4(int n)
{
label4.Text = n.ToString();
}
public void SetLable5(int n)
{
label5.Text = n.ToString();
}
public void SetLable6(int n)
{
label6.Text = n.ToString();
}
}
}