Search code examples
c#.netmultithreadingresumesuspend

Resuming C# threads


Possible duplicate question: Is there a way to indefinitely pause a thread?


In my code i do the below

Thread mainThread
//...
mainThread.Resume();

void StartThread()
{
    while (!wantQuit)
    {
        db.runEmail();
        mainThread.Suspend();
    }
}

Then i get the exception below because i call resume when it hasnt been suspended.

System.Threading.ThreadStateException

I notice this warning

warning CS0618: 'System.Threading.Thread.Resume()' is obsolete: 'Thread.Resume has been deprecated.  Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources.  http://go.microsoft.com/fwlink/?linkid=14202'

So i wonder is there a way to resume and ignore the exception/case that it is not suspended? I hate writing the below instead of just one line

        try
        {
            mainThread.Resume();
        }
        catch (System.Threading.ThreadStateException e)
        {
        }

Solution

  • The easy solution is to fix your logic and don't call Resume() when you are not Suspended().

    But the Resume/Suspend API is indeed deprecated, take a look at, for example:

    1) Monitor, Wait() and Pulse()

    2) AutoResetEvent or ManualResetEvent, Set() and WaitOne()

    The static class Monitor is a little easier to use and integrates with lock() {} , but a ResetEvent might be more appropriate here because you can create it in set or unset mode and you are less likely to 'miss' a signal. By contrast, a Monitor.Pulse() will just be lost when the Wait() happens later.


    Will inserted a link in your question, and while I don't consider it a duplicate, the accepted answer there is well suited to cure you from using Suspend/Resume.