I'm writing a C# library that contains a class which can start/pause/resume/cancel while it's doing work and have something like the following:
public class MyClass
{
...
bool _paused;
object key = new object(); //for locking
public void Start()
{
_paused = false;
//make new thread and start doing work....
}
public void Pause()
{
lock(key)
{
_paused = true;
}
}
public void Resume()
{
lock(key)
{
if(_paused)
{
_paused = false;
Thread t = new Thread(new ThreadStart(doWork));
t.Start();
}
}
}
private void doWork()
{
while(....)
{
lock(key)
{
if(_paused)
{
//save work state into some global object....
break; //stop doing work
}
}
//do work here....
}
}
} //end class
I want to know if the lock(key) in Resume() will persist into the doWork method or will the lock not persist into the doWork method? I'm unsure since it's a thread versus just another method call.
Question
ProChefChad
I'm writing a C# library that contains a class which can start/pause/resume/cancel while it's doing work and have something like the following:
public class MyClass { ... bool _paused; object key = new object(); //for locking public void Start() { _paused = false; //make new thread and start doing work.... } public void Pause() { lock(key) { _paused = true; } } public void Resume() { lock(key) { if(_paused) { _paused = false; Thread t = new Thread(new ThreadStart(doWork)); t.Start(); } } } private void doWork() { while(....) { lock(key) { if(_paused) { //save work state into some global object.... break; //stop doing work } } //do work here.... } } } //end classI want to know if the lock(key) in Resume() will persist into the doWork method or will the lock not persist into the doWork method? I'm unsure since it's a thread versus just another method call.
Thanks.
Link to comment
Share on other sites
3 answers to this question
Recommended Posts