It is a headache to write multiple threads with a single thread.
In C #, multithreading is very convenient, but synchronization becomes a big problem in the case of complex tasks. google has a lot of methods:
Lock
Monitor
Semaphores AutoResetEvent and ManualResetEvent
Mutex
I have tried it, but I can't synchronize it all the time. There will always be thread competition, and there will be no problem in single-line testing. The problem of multi-line is always inexplicable.
Debugging with the VS Debugger in multiple threads almost makes people crash.
Then I calmed down and finally figured out what was going on:
To change the way of thinking, the code in multithreading is always in competition, that is, the CPU is constantly polling. In fact, the CPU is always like this, but the multi-line is more obvious.
To execute the code in sequence, you can use an auxiliary thread to continuously query the status of multiple threads.
When necessary, you can use ManualResetEvent thread waitone () to check that all threads are in
When WaitSleepJoin is performed, You can execute the code you need to complete synchronization.
The enumerated constants defined in ThreadState are as follows:
Member name |
Description |
Aborted |
The thread is in the Stopped status. |
AbortRequested |
The Thread. Abort method has been called for the Thread, but the Thread has not received the pending System. Threading. ThreadAbortException trying to terminate it. |
Background |
The thread is being executed as the background thread (relative to the foreground thread ). This status can be controlled by setting the Thread. IsBackground attribute. |
Running |
The thread has been started, it is not blocked, and there is no pending ThreadAbortException |
Stopped |
Thread stopped |
StopRequested |
Requesting thread to stop. This is only used internally |
Sushortded |
Thread suspended |
SuspendRequested |
Pending request thread |
Unstarted |
The Thread. Start method has not been called for the Thread |
WaitSleepJoin |
The thread has been blocked because Wait, Sleep, or Join is called. |
From the column rztyfx