. NET brief introduction to component programming (multithreading and concurrency management I)

Source: Internet
Author: User

I will use several articles to explain the multi-threaded content.
Multithreading is widely used in our daily development process.. NET short talk about component programming (asynchronous delegation) "describes in detail the use of multiple threads Based on delegation, the principle of delegation is based on the background thread pool, this article mainly introduces how to use Thread objects to implement multithreading.
Of course, using Thread is not as easy as using Delegate. After all, multithreading and asynchronous calling are two very different technical directions. I also have a little bit of knowledge and I am sorry to give it to you here, if anything is wrong, please point it out. [Wang qingpei has all rights reserved. For more information, please sign it.]
Let's first understand several concepts to facilitate our learning.
Background thread and foreground thread
Foreground Thread: What is foreground Thread, that is, the foreground Thread is created using the default Thread without setting the IsBackground attribute, because the default IsBackground is false. The foreground thread specifies the task, that is, the program will not automatically exit before any foreground thread ends, unless the application is forcibly closed.
Background Thread: the background Thread is for the foreground Thread. if IsBackground is set to true, It is the background thread, and the background thread serves the foreground thread. That is to say, the background thread does not have a strong vitality. As long as the foreground thread ends, the background thread ends forcibly, even if the task is not completed. Therefore, we should select the actual situation when using it. [Wang qingpei has all rights reserved. For more information, please sign it.]
Thread Switching
Let's look at a piece of code to facilitate the introduction of theme.
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Threading;
Using System. Runtime. Remoting;
Using System. Runtime. Remoting. Contexts;
 
Namespace ConsoleApplication1. multithreading and concurrency Management
{
Public class MyClass
{
Public void ShowMessage ()
{
Thread currentthread = Thread. CurrentThread;
Console. WriteLine (currentthread. Name + currentthread. ManagedThreadId );
}

}
}
This is a simple piece of code. It is a ShowMessage method. There is a static attribute Thread. CurrentThread in the method to get the current context Thread, and then enter the Thread name and managed ID;
Namespace ConsoleApplication1. multithreading and concurrency Management
{
Public static class Program
{
Static void Main (string [] args)
{
Thread currentthread = Thread. CurrentThread;
Currentthread. Name = "main thread ";
Console. WriteLine (currentthread. Name + currentthread. ManagedThreadId );
 
MyClass myclass = new MyClass ();
ThreadStart start = new ThreadStart (myclass. ShowMessage );
Thread thread = new Thread (start );
Thread. Name = "subthread ";
Thread. Start ();
 
Thread. Sleep (1000); // Sleep, Thread Switching
Console. WriteLine (currentthread. Name + currentthread. ManagedThreadId );
Console. Read ();
}
}
}
 
This is the call code. I will give the main thread a name and then output it. I created a thread Thread. This is a subthread. We call the method defined above and use the same thread. CurrentThread to obtain the current context Thread. At last, let the main thread sleep for one second.
 
The figure clearly shows that the system automatically switches the thread in the background and obtains the current thread object using the same static variable.
The Sleep method is used to break the current thread for Sleep at a specified time. Even if the current thread is running on the CPU, the system immediately discards the time slice that the CPU has given it once Sleep is called and enters the blocking state.
[A thread is only the execution path in a process]
In fact, the thread is the execution path, and the system maintains a set of commands for the execution path, when multiple threads are enabled, we actually store a lot of commands to be executed in a command set. In other words, the commands are thread queues, use the CPU to execute the time slice.
Then the thread must be in a series of states, which are maintained by the OS, because the thread is an object at the kernel layer and can only be monitored by the OS in real time. We only need to use it. If you are interested, you can refer to Jeffrey Richter, Windows core programming (version 5th.
Let the thread wait rather than Switch
Sleep forces you to discard the CPU time slice and repeat it with other threads to compete with the CPU. Using Sleep will give up the CPU usage right for the Thread, and if we change to Thread. spinWait (100000000) won't give up the CPU's right to use. It just allows the CPU to execute a piece of useless code. After the time is over, it can be executed immediately, instead of competing with the CPU again.
This may not be important when the system resources are rich, but when the resources are insufficient and the CPU is not very good, I think this can improve the performance.
An important concept has to be put forward here: the caller of the thread and the main body of the thread. The caller of the thread is the client of the thread and another thread, rather than the current thread.
Thread. Join () connection Thread
The join method literally refers to the meaning of the connection. It is really hard to understand what the join method is. See the following code:
Thread currentthread = Thread. CurrentThread;
Currentthread. Name = "main thread ";
Console. WriteLine (currentthread. Name + currentthread. ManagedThreadId );
 
 
MyClass myclass = new MyClass ();
ThreadStart start = new ThreadStart (myclass. ShowMessage );
Thread thread = new Thread (start );
Thread. Name = "subthread ";
Thread. Start ();
 
Thread. Join (); // block the thread of the subthread until the thread execution of the subthread ends.
 
Console. WriteLine (currentthread. Name + currentthread. ManagedThreadId );
Console. Read ();
Through Join, we can wait for the thread to end. The connection means to connect me to the thread I called. I will continue to execute it after the end of the thread, here is the relationship between the main thread and the sub-thread. Only after the sub-thread technology, the main thread can continue to execute.
Thread. Abort terminate the Thread
Abort can be used to terminate a thread in execution, but Abort will cause a ThreadAbortException exception on the thread.
Public void DoWork ()
{
Try
{
Int I = 0;
While (true)
{
Console. WriteLine (Thread. CurrentThread. ManagedThreadId + "|" + I ++ );
If (I = 100)
{
Console. WriteLine ("---------------------------------------------");
Console. Read ();
Break; // exit the current thread for execution. Try not to end with Abort
}
}
}
Catch (ThreadAbortException err)
{
Console. WriteLine (err. Message + "11 ");
}
}
Thread currentthread = Thread. CurrentThread;
Console. WriteLine (currentthread. Name + currentthread. ManagedThreadId );
 
MyClass myclass = new MyClass ();
ThreadStart start = new ThreadStart (myclass. DoWork );
Thread thread = new Thread (start );
Thread. Start ();
 
Thread. Sleep (5000 );
Console. WriteLine (currentthread. Name + currentthread. ManagedThreadId + "end-to-end subthread ");
Thread. Abort ();
Console. Read ();

Thread. IsBackground = true background Thread
By setting IsBackground, the thread can be placed in the background thread. As long as the foreground thread ends, the background thread is automatically terminated.
Public void DoWork ()
{
Try
{
Int I = 0;
While (true)
{
Console. WriteLine (Thread. CurrentThread. ManagedThreadId + "|" + I ++ );
// If (I = 100)
//{
// Console. WriteLine ("---------------------------------------------");
// Console. Read ();
// Break; // exit the current thread for execution and try not to end with Abort
//}
}
}
Catch (ThreadAbortException err)
{
Console. WriteLine (err. Message + "11 ");
}
Comment out a piece of code.
Thread currentthread = Thread. CurrentThread;
Console. WriteLine (currentthread. Name + currentthread. ManagedThreadId );
 
MyClass myclass = new MyClass ();
ThreadStart start = new ThreadStart (myclass. DoWork );
Thread thread = new Thread (start );
Thread. IsBackground = true;
Thread. Start ();
 
Thread. Sleep (2000 );
Console. WriteLine (currentthread. Name + currentthread. ManagedThreadId );
This is the call code. As long as the foreground thread does not end, the background thread continues to execute. If we add the Console. ReadLine (); Code at the end, the background thread will always run.
 
Conclusion: This article is over first. In the next article, we will learn about the concept of synchronous domain and context.
This article is from the "Deep training (DotNet session)" blog

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.