I’ve been working on a web crawling .NET app in my free time, and one of the features of this app that I wanted to included was a pause button to pause a specific thread.
I’m relatively new to multi-threading and I haven’t been able to figure out a way to pause a thread indefinitely that is currently supported. I can’t remember the exact class/method, but I know there is a way to do this but it has been flagged as obsolete by the .NET framework.
Is there any good general purpose way to indefinitely pause a worker thread in C# .NET.
I haven’t had a lot of time lately to work on this app and the last time I touched it was in the .NET 2.0 framework. I’m open to any new features (if any) that exist in the .NET 3.5 framework, but I’d like to know of solution that also works in the 2.0 framework since that’s what I use at work and it would be good to know just in case.
Never, ever use
Thread.Suspend. The major problem with it is that 99% of the time you can’t know what that thread is doing when you suspend it. If that thread holds a lock, you make it easier to get into a deadlock situation, etc. Keep in mind that code you are calling may be acquiring/releasing locks behind the scenes. Win32 has a similar API:SuspendThreadandResumeThread. The following docs forSuspendThreadgive a nice summary of the dangers of the API:http://msdn.microsoft.com/en-us/library/ms686345(VS.85).aspx
The proper way to suspend a thread indefinitely is to use a
ManualResetEvent. The thread is most likely looping, performing some work. The easiest way to suspend the thread is to have the thread ‘check’ the event each iteration, like so:You specify an infinite timeout so when the event is not signaled, the thread will block indefinitely, until the event is signaled at which point the thread will resume where it left off.
You would create the event like so:
The
trueparameter tells the event to start out in the signaled state.When you want to pause the thread, you do the following:
And to resume the thread:
You can use a similar mechanism to signal the thread to exit and wait on both events, detecting which event was signaled.
Just for fun I’ll provide a complete example: