In unmanaged code you can create a thread in suspended state. In .NET Framework I can't find this option. 开发者_如何学PythonIs it because the Thread constructor puts the thread in a suspended state? Is there other reason why this is not supported?
When you create a new Thread
, its ThreadState
is ThreadState.Unstarted
, not ThreadState.Suspended
.
This may correspond to a suspended thread at the OS level; however, the implementation details of a managed thread are something you should not be concerning yourself with. .NET threads are more than just simple wrappers around unmanaged threads.
You may also note that the Suspend
and Resume
methods of the Thread
class are marked as obsolete, with this scary warning:
Do not use the Suspend and Resume methods to synchronize the activities of threads. You have no way of knowing what code a thread is executing when you suspend it. If you suspend a thread while it holds locks during a security permission evaluation, other threads in the AppDomain might be blocked. If you suspend a thread while it is executing a class constructor, other threads in the AppDomain that attempt to use that class are blocked. Deadlocks can occur very easily.
Directly suspending and resuming threads is highly discouraged in .NET, and if you started a thread "as suspended", then you would have to Resume
it. They want to discourage people from using any of these methods, so instead they use the special Unstarted
status and get you to Start
the thread instead of Resuming
it. It's a much cleaner abstraction anyway.
Summary: The option is not directly available to you because you are not supposed to be suspending or resuming threads at all - leave that up to the .NET runtime, or even better, use the ThreadPool
when you can.
精彩评论