views:

1522

answers:

5

The two methods Suspend() and Resume() are obsolete in C# .Net 2.0. What are other alternatives and any examples?

+2  A: 

This is the best tutorial ever for Thread (for C#): http://www.albahari.com/threading/

For wait you need to use .Join() on the thread. This will wait until tread finish is job. Other wise you will need to use Wait/Pulse.

Daok
+5  A: 

The good alternatives all work by the thread reaching a point where it is happy to wait. Suspend was dangerous because it could suspend the thread while it was holding a lock on a mutex - a recipe for deadlocks.

So what your thread needs is a ManualResetEvent that it can Wait on - at a time when it is safe for it to do so, when it is not holding any locks.

Daniel Earwicker
Good point with the ManualResetEvent. You can also use an AutoResetEvent.
siz
A: 

I agree that is a great tutorial. The main reason Suspend() and Resume() are obsolete is because they are pretty dangerous methods. At any point Thread t could be doing anything. Anything. Imagine your thread is reading a file and has a lock on it. You suspend your thread. File stays locked. Same goes for any other resources. Same goes for a lock on a mutex.

siz
+1  A: 

That one is too long. What I need is a quick example codes to use. I found one from the discussion and answered by Mark R. Dawson at http://bytes.com/groups/net-c/458947-thread-suspend. It explains the danger of the obsolete methods and how to use AutoResetEvent to notify the second thread to continue processing.

David.Chu.ca
+2  A: 

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".

Darcy Casselman
This solves typical Suspend/Resume situations and avoids obsolete warnings.
Marc Climent