Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are alternative ways to suspend and resume a thread?

The two methods Thread.Suspend() and Thread.Resume() are obsolete since .NET 2.0. Why? What are other alternatives and any examples?

like image 928
David.Chu.ca Avatar asked Dec 19 '08 20:12

David.Chu.ca


People also ask

What can I use instead of thread suspension?

Suspend has been deprecated. Use other classes in System. Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources.

Which method is used to resume the suspended thread and obsolete?

The suspend() method of thread class puts the thread from running to waiting state. This method is used if you want to stop the thread execution and start it again when a certain event occurs. This method allows a thread to temporarily cease execution. The suspended thread can be resumed using the resume() method.

What is the difference between suspend () and resume () methods?

In this case, the suspend() method allows a thread to temporarily cease executing. resume() method allows the suspended thread to start again.

How we can resuming the thread?

The resume() method of thread class is only used with suspend() method. This method is used to resume a thread which was suspended using suspend() method. This method allows the suspended thread to start again.


1 Answers

You'll want to use an AutoResetEvent EventWaitHandle.

Say you want to do something like this (NOTE: don't do this!):

private Thread myThread;  private void WorkerThread()  {     myThread = Thread.CurrentThread;     while (true)     {         myThread.Suspend();         //Do work.     } }  public void StartWorking()  {     myThread.Resume(); } 

Like others have said, this is a bad idea. Even though only using Suspend on its own thread is relatively safe, you can never figure out if you're calling Resume when the thread is actually suspended. So Suspend and Resume have been obsoleted.

Instead, you want to use an AutoResetEvent:

private EventWaitHandle wh = new AutoResetEvent();  private void WorkerThread()  {     while(true)      {         wh.WaitOne();         //Do work.     } }  public void StartWorking() {     wh.Set(); } 

The worker thread will wait on the wait handle until another thread calls StartWorking. It works much the same as Suspend/Resume, as the AutoResetEvent only allows one thread to be "resumed".

like image 118
Darcy Casselman Avatar answered Sep 20 '22 03:09

Darcy Casselman