I'm trying to start thread and then end thread by clicking buttons in Winform
but the MessageBox
does not appear after clicking the Stop
button( which is the button 3
here). \
Here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace ThreadForm
{
public partial class Form1 : Form
{
public static volatile bool isPausePressed = false;
Thread SequenceTest = new Thread(DoWork);
Thread Seq1Test = new Thread(TestSequence1);
Thread Seq2Test = new Thread(TestSequence2);
Thread Seq3Test = new Thread(TestSequence3);
public Form1()
{
InitializeComponent();
}
Form2 objform;
private void button1_Click(object sender, EventArgs e)
{
objform = new Form2();
objform.Show();
var formWithButton = new Form2();
formWithButton.Btn_Change.BackColor = Color.White;
SequenceTest.Start();
Seq1Test.Start();
Seq2Test.Start();
Seq3Test.Start();
}
private void button2_Click(object sender, EventArgs e)
{
isPausePressed = true;
}
private void button3_Click(object sender, EventArgs e)
{
bool a, b, c, d;
a = b = c = d = false;
SequenceTest.Join();
/*if (SequenceTest.ThreadState == System.Threading.ThreadState.Stopped)
a = true;*/
Seq1Test.Join();
/*if (Seq1Test.ThreadState == System.Threading.ThreadState.Stopped)
b = true;*/
Seq2Test.Join();
/*if (Seq2Test.ThreadState == System.Threading.ThreadState.Stopped)
c = true;*/
Seq3Test.Join();
/*if (Seq3Test.ThreadState == System.Threading.ThreadState.Stopped)
d = true;*/
MessageBox.Show("Done!", "ThreadTest");
}
public static void DoWork()
{
Thread.Sleep(1000);
//Console.WriteLine("Current main task working on thread: {0}", Thread.CurrentThread.ManagedThreadId);
while (!isPausePressed)
{
Thread.Sleep(100);
}
}
public static void TestSequence1()
{
int i = 0;
Thread.Sleep(1000);
//Console.WriteLine("Sequence1 working on thread: {0}", Thread.CurrentThread.ManagedThreadId);
while (true)
{
i++;
//Console.WriteLine("Current i value: {0}", i);
}
}
public static void TestSequence2()
{
int j = 0;
//Console.WriteLine("Sequence2 working on thread: {0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1000);
while (true)
{
j++;
//Console.WriteLine("Current j value: {0}", j);
}
}
public static void TestSequence3()
{
int k = 0;
Thread.Sleep(1000);
//Console.WriteLine("Sequence3 working on thread: {0}", Thread.CurrentThread.ManagedThreadId);
while (true)
{
k++;
//Console.WriteLine("Current k value: {0}", k);
}
}
}
}