I'm trying to use ManualResetEvent
to start, pause, resume and terminate thread by referring to Stopping a Thread, ManualResetEvent, volatile boolean or cancellationToken . I'm confused with Set()
and WaitOne()
. Here's my code and I will need some help for the changes that have to be made so that I can resume after pausing the thread and stop entirely then I can start again the work without closing the whole winform.
namespace ThreadForm
{
public partial class Form1 : Form
{
public static volatile bool isPausePressed = false;
private static EventWaitHandle waitHandle = new ManualResetEvent(initialState: true);
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;
if (SequenceTest.IsAlive)
{
waitHandle.Set();
}
else
{
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)
{
waitHandle.Reset();
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 (i!=10)
{
i++;
//Console.WriteLine("Current i value: {0}", i);
}
isPausePressed = true;
}
public static void TestSequence2()
{
int j = 0;
//Console.WriteLine("Sequence2 working on thread: {0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1000);
while (j != 10)
{
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 (k != 10)
{
k++;
//Console.WriteLine("Current k value: {0}", k);
}
}
}
}