码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-12-05 17:38:21      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

 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 }

 

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

标签:

原文地址:http://www.cnblogs.com/laresh/p/5021715.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!