コード例 #1
0
ファイル: Form1.cs プロジェクト: zyloveyh/WindowsFormsApp1
        private void button1_Click_1(object sender, EventArgs e)
        {
            System.Windows.Forms.Button allBtn = (System.Windows.Forms.Button)sender;
            if (allBtn.Text.Equals("全部执行"))
            {
                allBtn.Enabled = false;
                //点击了全部执行按钮,便禁用单条执行按钮
                overTurnBtnState(false);
                allBtn.Text = "停止";
                //开始执行线程

                List <QuestionaireEntity> questionList = QuestionaireData.result;

                foreach (var q in questionList)
                {
                    //设置终止线程状态为false
                    q.CloseThread = false;
                    //先判断线程集合中是否有这个线程
                    if (CreateController.threadDict.ContainsKey(q.SeriaNum))
                    {
                        //已经有此线程执行了,直接跳过
                        continue;
                    }
                    //新建刷题线程
                    Thread thread = new Thread(() => CreateController.exercise(this, q));
                    //加入到线程集合中
                    CreateController.threadDict.Add(q.SeriaNum, thread);
                    thread.Name = q.SeriaNum;
                    //启动线程
                    thread.Start();
                }
                allBtn.Enabled = true;
            }
            else
            {
                List <QuestionaireEntity> questionList = QuestionaireData.result;
                foreach (var q in questionList)
                {
                    //设置终止线程状态为false
                    q.CloseThread = true;
                }
                allBtn.Text = "正在停止...";

                /**
                 * allBtn.Enabled = false;
                 * //点击了停止 按钮,便停止刷单
                 * overTurnBtnState(true);
                 * allBtn.Text = "全部执行";
                 * //关闭所有的线程
                 * Dictionary<string, Thread>.ValueCollection threads = CreateController.threadDict.Values;
                 * foreach (var th in threads)
                 * {
                 *  th.Abort();
                 *  while (th.ThreadState != ThreadState.Aborted)
                 *  {
                 *      //当调用Abort方法后,如果thread线程的状态不为Aborted,主线程就一直在这里做循环,直到thread线程的状态变为Aborted为止
                 *      Thread.Sleep(100);
                 *  }
                 *
                 * }
                 **/
            }
        }