• 0

[C#] - lock(....) and new Thread


Question

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.

Thanks.

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

From what I understand of the lock keyword in C# using lock on an object that doesn't get used might as well not be there, because it just puts a lock on that object within the class during execution of the code block, releasing it for other threads after the block is executed.

lock(this)

Would protect the whole object during the method call, which seems like what you want? The lock should persist, but only on the object you specify. So in this case only "key" is protected, whereas "this" should mean that Resume won't run until Start has Finished.

Link to comment
Share on other sites

  • 0

MiG - Thanks for your response. However, it looks like this MSDN article contradicts what you said about using lock(this) versus using lock(<some private object for locking>).

The question I really have is I want to know if my lock will continue to exist within the new Thread I create within the lock:

public void Resume()
{
	lock(key)
	{
		if(_paused)
		{
			_paused = false;

			Thread t = new Thread(new ThreadStart(doWork));  //Will doWork() still have a lock on 'key'????
			t.Start();
		}
	}
}

In the end, what I've changed Resume to is:

		public void Resume()
		{
			bool StartThread = false;

			lock (key)
			{
				if (_paused)
				{
					_paused = false;
					StartThread = true;
				}
			}

			if (StartThread)
			{
				//Start the crawling process on a new thread
				Thread t = new Thread(new ParameterizedThreadStart(doWork));
				t.Start();
			}
		}

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.