Archive | April, 2013

Sample to create, start, pause, resume and terminate a Thread in C#

21 Apr

This example demonstrates how to create a worker Thread to do some work without affecting the main thread. This worker thread also give us an effective way to pause and resume the thread without using Thread.Suspend . The major problem with Thread.Suspend is that you never know what the thread was doing when you call suspend on the thread. The thread might be in critical section or mutex which can lead to deadlock. The proper way to suspend the thread indefinitely is to use a ManualResetEvent. The thread when running will check for event in each iteration when performing some work. Here is a complete example to demonstrate this.

public class Worker
{
 ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
 ManualResetEvent _pauseEvent = new ManualResetEvent(true);
 Thread _thread;

public Worker() { }

public void Start()
 {
 _thread = new Thread(DoWork);
 _thread.Start();
 Console.WriteLine("Thread started running");
 }

public void Pause()
 {
 _pauseEvent.Reset();
 Console.WriteLine("Thread paused");
 }

public void Resume()
 {
 _pauseEvent.Set();
 Console.WriteLine("Thread resuming ");
 }

public void Stop()
 {
 // Signal the shutdown event
 _shutdownEvent.Set();
 Console.WriteLine("Thread Stopped ");

// Make sure to resume any paused threads
 _pauseEvent.Set();

// Wait for the thread to exit
 _thread.Join();
 }

public void DoWork()
 {
 while (true)
 {
 _pauseEvent.WaitOne(Timeout.Infinite);

if (_shutdownEvent.WaitOne(0))
 break;

// Do the work..
 Console.WriteLine("Thread is running");

 }
 }
}

For more information refer below links

http://stackoverflow.com/questions/142826/is-there-a-way-to-indefinitely-pause-a-thread/143153#143153

Design a site like this with WordPress.com
Get started