Fork me on GitHub

青禹小生

雁驰万里却作禽,鱼未得水空有鳞。 花开花落花不语,昨是昨非昨亦今。

导航

利用多线程写一个摇奖机小程序

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading;
 9 using System.Threading.Tasks;
10 using System.Windows.Forms;
11 
12 namespace yaojiangji
13 {
14     public partial class Form1 : Form
15     {
16         private List<Label> lbList = new List<Label>();
17         private bool isRunning = false;
18         public Form1()
19         {
20             InitializeComponent();
21         }
22 
23         private void Form1_Load(object sender, EventArgs e)
24         {
25             for (int i = 0; i <6; i++)
26             {
27                 Label lb = new Label();
28                 lb.Text = "0";
29                 lb.AutoSize = true;
30                 lb.Location = new Point(60*i+60,100);
31                 this.Controls.Add(lb);
32                 lbList.Add(lb);
33                 
34             }
35 
36         }
37 
38         private void btnStartOrStop_Click(object sender, EventArgs e)
39         {
40             if (isRunning == false)
41             {
42                 isRunning = true;
43                 btnStartOrStop.Text = "停止";
44                 Thread thread = new Thread(() =>
45                 {
46                     Random r = new Random();
47                     while (isRunning)
48                     {
49                         foreach (var item in lbList)
50                         {
51                             string str = r.Next(0, 10).ToString();
52                             if (item.InvokeRequired)
53                             {
54                                 item.Invoke(new Action<string>(s => { item.Text = s; }), str);
55                             }
56                             else
57                             {
58                                 item.Text = str;
59                             }
60 
61                         }
62                         Thread.Sleep(50);
63 
64                     }
65 
66                 });
67                 thread.IsBackground = true;
68                 thread.Start();
69             }
70             else
71             {
72                 isRunning = false;
73                 btnStartOrStop.Text = "开始";
74 
75             }
76         }
77     }
78 }

 

posted on 2015-12-05 15:57  司徒道  阅读(636)  评论(0编辑  收藏  举报