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


     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 }
  • 相关阅读:
    C# 导入Excel遇到数字字母混合列数据丢失解决
    C# 导出 Excel
    DataGridView 改变行列颜色
    EditPlus使用技巧
    jquery的事件与应用
    jquery操作DOM元素的复习
    jquery笔记
    jquery 和ajax
    jQuery笔记
    CSS相关知识三
  • 原文地址:https://www.cnblogs.com/laresh/p/5021715.html
Copyright © 2020-2023  润新知