. Net multi-thread summary and. net multi-thread Summary
1. Brief Introduction
Generally, a program is a process in which the code exists. The process itself does not execute the code, and the code is executed by a thread.
Generally, a process is a thread. (A store is a lady in charge .)
A process opens up a space in the memory. Code, image .. And so on. Run the code thread.
By default, there is only one thread.
Systerm. threading // the class for thread operations is in this namespace.
2. foreground and background threads.
To enable a thread, create a thread object.
By default, all threads are foreground threads.
The program will exit after all foreground threads are executed.
The default thread in a process is the main thread, the default thread, or the UI thread.
Background threads. As long as all foreground threads end, all background threads end directly.
Thread th = new Thread (Sum); th. Name = "Thread 1"; Name the Thread. You can see the specific name in the output during debugging. Th. IsBackground = true; th. Start (); th. Abort (); forcibly terminate the thread. Thread. Sleep (1000); pause the Thread. The unit is millisecond Thread cuTh = Thread. CurrentThread to get the reference of the current Thread. Thread type. TextBox. checkforillegalcrossthreadcils = false; // disable cross-thread access checks for space. Otherwise, the following error occurs:
3. Thread re-import
Multiple threads in the same process can be executed concurrently.
Multiple Threads access the same resource, which may cause non-synchronization. This is called thread re-entry.
In this case, locks can be applied.
private void CountNum() { lock (this) { for (int i = 0; i < 10000; i++) { int num = int.Parse(textBox1.Text.Trim()); num++; textBox1.Text = num.ToString(); } } }
4. thread object nature (delegate) 4.1 A delegate object needs to be passed through the no-argument method.
ThreadStart ts = new ThreadStart (CountNum); Thread th = new Thread (ts); equivalent to Thread th = new Thread (CountNum); essentially a delegate object. (CountNum is the method without parameters)
4.2 method with Parameters
If you need to pass the parameter method.
It is the delegate object of the ParameterizedThreadStart created.
Parameters are passed in the Start method. The start method has two overloading methods.