Reputation:
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)
{
}
Upvotes: 3
Views: 1592
Reputation: 273179
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.
Upvotes: 7
Reputation: 564373
WaitHandles are a better approach here.
Instead of suspending your thread, have it wait on a waithandle. When you are ready to start up again, you "set" the handle from the other thread.
For a code example, see MSDN's documentation of ManualResetEvent.
Upvotes: 2
Reputation: 56500
You can check Thread.ThreadState and check for ThreadState.Suspended before resuming.
Upvotes: 0
Reputation: 441
You might want to take a look at using a Thread Monitor in this case.
Upvotes: 0