private void start_btn_Click(object sender, EventArgs e) { if (running) { paused = false; status_lbl.Text = "Running"; return; } ResetColor(); List <Instruction> instructions = new List <Instruction>(); for (int i = 0; i < dataGridView1.RowCount - 1; i++) { string row = dataGridView1[0, i].Value?.ToString() ?? ""; string[] str = row.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (str.Length < 2) { MessageBox.Show("Bad instruction: " + row, "", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } for (int j = 0; j < 2; j++) { if (str[j] == EMPTY_CODE) { str[j] = ""; } } instructions.Add(new Instruction(str[0], str[1], str.Length == 3 && str[2] == "*")); } history.Items.Clear(); status_lbl.Text = "Running"; paused = false; stopped = false; running = true; new Task(() => { Markov markov = new Markov(instructions); try { markov.Execute(word_textbox.Text, m => { int delay = 0; this.Invoke(new Action(() => { word_textbox.Text = m.Word; delay = (int)delay_upDown.Value; if (m.LastInstructionIndex != -1) { history.Items.Insert(0, m.LastInstruction + ": " + m.Word); last_instr_lbl.Text = m.LastInstruction.ToString(); dataGridView1.ClearSelection(); dataGridView1.Rows[m.LastInstructionIndex].Selected = true; if (mark_check.Checked) { dataGridView1.Rows[m.LastInstructionIndex].DefaultCellStyle.BackColor = Color.Lime; } } if (progressbar.Value == progressbar.Maximum) { progressbar.Value = 0; } else { progressbar.Value += 33; } })); Thread.Sleep(delay); while (paused && !stopped) { Thread.Sleep(delay); } if (stopped) { m.Stop(); } }); } catch (Exception exception) { MessageBox.Show(exception.Message); } this.Invoke(new Action(() => { running = false; status_lbl.Text = "Stopped"; progressbar.Value = 0; })); }).Start(); }