In my windows forms application, I start a thread to do some work.
I need to be able to pause what that thread is doing without having to restart the whole thread or start a new thread.
I have some code but somehow it does not look thread safe. It appears to work, but I'm sure that does not mean that it will not run into a race problem.
I have reproduced some minimalistic code to show what I'm doing, and I'm hoping someone might advise me a better way to accomplish my goal, which is basically that two methods called from separate threads might try to read the some bool field (paused) at the same time.
Thanks for reading.
namespace CSThreadingTest
{
public delegate void ThreadDelegate();
public partial class Form1 : Form
{
private bool paused = false;
private int counter = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.start.Enabled = false;
Thread t = new Thread(new ThreadStart(MyThread));
t.IsBackground = true;
t.Start();
}
//Thread method started with start button
private void MyThread()
{
while (true)
{
if (!paused)
{
Invoke(new ThreadDelegate(Count));
}
Thread.Sleep(500);
}
}
// Method that thread invokes
private void Count()
{
myTextbox.Text = counter.ToString();
counter++;
}
//Pause button
private void button2_Click(object sender, EventArgs e)
{
paused = !paused;
}
}
}