超级大乐透的例子,多线程

超级大乐透规约:“35选5加12选2”

从01-35个号码,选取5个号码作为前区号码

从01-12个号码,选取2个号码作为后期号码

首先建一个Form界面

 

 点击【结束】后,如下图

 

 

  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 _19_Games
 13 {
 14     public partial class frmHappy : Form
 15     {
 16         public static readonly object objLock = new object();//官方标准锁
 17         public CancellationTokenSource cts;
 18         string[] strBlueBuff = new string[] {
 19             "01", "02","03","04","05","06", "07","08","09","10",
 20              "11", "12"
 21         };
 22         string[] strRedBuff = new string[] {
 23             "01", "02","03","04","05","06", "07","08","09","10",
 24              "11", "12","13","14","15","16","17","18","19","20",
 25              "21", "22","23","24","25","26","27","28","29","30",
 26             "31","32","33","34","35"
 27         };
 28 
 29 
 30         public frmHappy()
 31         {
 32             InitializeComponent();
 33         }
 34         private void button1_Click(object sender, EventArgs e)
 35         {
 36             SaveInvok(() =>
 37             {
 38                 List<Task> tasksList = new List<Task>();
 39                 lblRed1.Text = "00";
 40                 lblRed2.Text = "00";
 41                 lblRed3.Text = "00";
 42                 lblRed4.Text = "00";
 43                 lblRed5.Text = "00";
 44                 lblBlue1.Text = "00";
 45                 lblBlue2.Text = "00";
 46                 btnStart.Text = "进行中...";
 47                 cts = new CancellationTokenSource();
 48                 foreach (var item in this.groupBox1.Controls)
 49                 {
 50                     if (item is Label)
 51                     {
 52                         Label label = (Label)item;
 53                         if (label.Name.Contains("Blue"))
 54                         {
 55                             tasksList.Add(Task.Factory.StartNew(() =>
 56                            {
 57                                Console.WriteLine($"==blue={Thread.CurrentThread.ManagedThreadId}===");
 58                                DoWork(label, strBlueBuff, "Blue");
 59                            }, cts.Token));
 60                         }
 61                         else
 62                         {
 63                             tasksList.Add(Task.Factory.StartNew(() =>
 64                            {
 65                                Console.WriteLine($"=red=={Thread.CurrentThread.ManagedThreadId}===");
 66                                DoWork(label, strRedBuff, "Red");
 67                            }, cts.Token));
 68                         }
 69                     }
 70                 }
 71 
 72                 //界面都是非0的时候,关闭按钮亮起来
 73                 #region
 74                 //while(true)//死锁了。主线程等子线程更新数据;子线程等主线程来更新
 75                 //{
 76                 //    Thread.Sleep(1000);
 77                 //    if (!IsExist("00") && lblBlue.Text != "00")
 78                 //    {
 79                 //        this.btnStart.Enabled = true;
 80                 //        break;
 81                 //    }
 82                 //}
 83                 Task.Factory.StartNew(() =>
 84                 {
 85                     while (true)
 86                     {
 87                         Console.WriteLine($"==={Thread.CurrentThread.ManagedThreadId}===");
 88                         if (!IsExist("00", "Blue") && !IsExist("00", "Red"))
 89                         {
 90                             this.Invoke(new Action(() => { btnEnd.Enabled = true; }));
 91                             break;
 92                         }
 93                     }
 94                 });
 95                 #endregion
 96 
 97                 //所有线程结束的时候,弹出窗体展示数据,两种方式都可以实现
 98                 #region
 99                 //用TaskFactory实现
100                 //TaskFactory taskFactory = new TaskFactory();
101                 //taskFactory.ContinueWhenAll(tasksList.ToArray(), arrayItem => ShowNum());
102 
103                 //用Task实现
104                 Task.WhenAll(tasksList.ToArray()).ContinueWith(item =>
105                 {
106                     ShowNum();
107                     this.Invoke(new Action(() => { btnStart.Text = "开始"; }));
108                 });//有点装得啊,点击开始的时候,就注册了后续动作
109                 #endregion
110             });
111         }
112         private void ShowNum()
113         {
114             MessageBox.Show($"{lblRed1.Text},{lblRed2.Text},{lblRed3.Text},{lblRed4.Text},{lblRed5.Text},{lblBlue1.Text},{lblBlue2.Text}");
115         }
116         private void DoWork(Label label, string[] strBuf, string strColor)
117         {
118             while (true)
119             {
120                 if (cts.IsCancellationRequested)
121                 {
122                     break;
123                 }
124                 int num = new RandomHelper().GetRandomNumberLong(0, strBuf.Length);
125                 string strBlue = strBuf[num];
126                 lock (objLock)
127                 {
128                     if (IsExist(strBlue, strColor))
129                     {
130                         continue;
131                     }
132                     this.UpdateNum(label, strBlue);
133                 }
134             }
135         }
136         private void UpdateNum(Label item, string strBlue)
137         {
138             if (this.InvokeRequired)
139             {
140                 this.Invoke(new Action(() => { item.Text = strBlue; }));
141             }
142         }
143 
144         private bool IsExist(string strNum, string strColor)
145         {
146             foreach (var item in this.groupBox1.Controls)
147             {
148                 if (item is Label)
149                 {
150                     Label label = (Label)item;
151                     if (label.Name.Contains(strColor) && label.Text.Equals(strNum))
152                     {
153                         return true;
154                     }
155                 }
156             }
157             return false;
158         }
159 
160         private void button2_Click(object sender, EventArgs e)
161         {
162             SaveInvok(() =>
163             {
164                 if (cts != null)
165                 {
166                     cts.Cancel();
167                 }
168             });
169         }
170         public static void SaveInvok(Action action)
171         {
172             try
173             {
174                 action.Invoke();
175             }
176             catch (Exception ex)
177             {
178                 MessageBox.Show(ex.Message);
179             }
180         }
181     }
182 }

 

posted @ 2022-07-25 21:10  东方承丘  阅读(55)  评论(0编辑  收藏  举报