Detailed introduction to C#Thread bit by bit

黄舟
Release: 2017-03-20 13:17:17
Original
1797 people have browsed it

Made a simple timer using C#'s Thread. In order to allow you to take a break after 45 minutes, a music prompt will sound after 45 minutes.

The TimeSpan subtraction method used at the beginning was written like this in the startup function of Thread:

  1. public void CountTime()
    {
                
       while (true)
       {
          TimeSpan tsNew = new TimeSpan(DateTime.Now.Ticks);
          TimeSpan tsIn = tsNew - tsOld;
          if (tsIn.Minutes >= 1)
          {
        
             while (true)
             {
                 TimeSpan tsNewer = new TimeSpan(DateTime.Now.Ticks);
                 TimeSpan tsIner = tsNewer - tsNew;
                 if (tsIner.Minutes >= 10)
                 {
                    //十分钟后线程重启
                     tsOld = tsNew;
                     break;
                 }
             }
             
           }
       }
    }
    Copy after login

Later I discovered this The method is too inefficient. Of course, you can use Thread.Sleep(20); this function to reduce CPU usage time. In fact, adding Thread.Sleep(20); in the middle can significantly reduce CPU consumption. Later I discovered that Thread in C# has its own function join(), which can make the thread wait for a period of time. The calling method is as follows

th.Join(new TimeSpan(hours, minutes, seconds)); During the waiting period, the thread is in WaitSleepJoin state.

Of course you can also call Thread.Sleep(millionseconds); here is the difference between Sleep and Join

##When the thread executes Sleep, the system exits the execution queue After a while, when the sleep ends, the system will generate a clock interrupt, causing the thread to return to the execution queue to resume the execution of the thread. If the parameter of the Sleep method is 0, it means that this thread should be suspended to let other waiting threads run. Here, the CPU will redistribute control rights, or it may be the program that was just executed. In this way, the CPU usage will always be 100%. Sometimes your interface is dead, but you can still move the mouse. If it is Timeout.Infinite, it means that the thread will sleep until it is interrupted by another thread that calls Thread.Interrupt or is aborted by Thread.Abort.
If the parent thread ends before the child thread, the child thread will be forced to end at the same time as the parent thread ends. The Thread.Join() method causes the parent thread to wait until the child thread ends. The Join method has a return value. When the value is true, it means the thread is terminated. If false, it means that the thread has not terminated after waiting for that period of time. If the thread is in the Unstarted state, calling join() will cause a ThreadStateException exception. If the thread has terminated, calling this function will get the return value immediately.

For example, the following main program

...
ThreadStart st = New ThreadStart(fun);
Thread th = new Thread(ThreadStart st);
th.Start();
Application.Exit();
...
 
//下面是fun函数
void fun()
{
    while(true)
    {
            ...
    }
}
Copy after login

The only problem with this program is that it is possible that after the main program exits, the slave thread it's not finished yet. (This slave thread is so pitiful...)

Here are some thread statuses:

 Creation: When a new process is created, a thread is also created for the process. Threads can also create new threads.

Ready: The thread has obtained all resources except the processor.

Running: The thread is executing on the processor.

Blocking: The thread is suspended due to waiting for a

event.

Termination: A thread has completed.

But there are several more states in the C# thread:

Aborted, AbortRequested, Background, Running, Stopped, StopRequested, Suspended, SuspendRequested, Unstarted, WaitSleepJoin.

Abort() will cause ThreadState.AbortRequested. After the thread that calls Abort() gains control, it will cause ThreadState.Aborted. The difference between AbortRequested and Aborted is that one is stopped and the other is not stopped. Stopped means the thread is terminated. However, I have tried and tested many times and found that when the Abort() function is called, the thread status will change to Stopped. How to change it to the Aborted state is still under study. The other states are similar. Calling the corresponding function will generate a corresponding status request, and it will take a while to get the corresponding status. As for Unstarted, it means that the Start() function has not been called, and Running is the result of calling the Start() or Resume() function. WaitSleepJoin is waiting for I/O, or calling the Join() method.

The difference between Join() and Sleep() methods here is that calling Join() thread state enters WaitSleepJoin, calling Sleep() thread state is still Running.

The method to suspend a thread is Suspend(); after calling this method, the thread is in the SuspendRequest state. If the thread is still executing the join() method after Suspended() is called, because Suspended() requires the thread to reach the safe point before it can suspend the thread. At this time, the thread status is SuspendRequested|WaitSleepJoin . But the clock in the join here is still counting. So I still don’t know what method to use to pause the join count. Of course, we can also solve the problem of completely suspending the thread without using join. Now I don't understand which Suspended() function does what, because the thread is still running. It is also worth mentioning that the use of Suspend() and the Resume() method that allows the thread to resume again after calling Suspend() is now deprecated. The reason is very simple, because these two methods are executed by other threads, and the other threads cannot accurately know the state of the thread being Suspend(), such as the structure of a certain class FunctionExecution period, or destruction, etc. So it is dangerous to use this function for synchronization.

#In addition, it should be noted that Thread.Sleep(n) n cannot control the time accurately. If you think how long it takes to thread, there is a problem with this control. If the current thread is a foreground thread, then Thread.Sleep(n) must be greater than n before it can exit. If it is a background process, when the main program exits, the thread can no longer be awakened... miserable... so it is generally recommended not to use the Thread.Sleep() function. In addition, the Sleep function cannot be used for synchronization. Peter said that the program's Sleep function represents a poor design.


The above is the detailed content of Detailed introduction to C#Thread bit by bit. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!