In this code I want to Pause/Resume a thread using an AutoResetEvent and a bool variable. Is is possible to Pause whithout testing each time (in for loop of Work()) if blocked==true? Testing of "blocked" variable needs locking also and i think this is time consuming.
class MyClass
{
AutoResetEvent wait_handle = new AutoResetEvent();
bool blocked = false;
void Start()
{
Thread thread = new Thread(Work);
thread.Start();
}
void Pause()
{
blocked = true;
}
void Resume()
{
blocked = false;
wait_handle.Set();
}
private void Work()
{
for(int i = 0; i < 1000000; i++)
{
if(blocked)
wait_handle.WaitOne();
Console.WriteLine(i);
}
}
}