Multithreading, as the name implies, is the implementation of multiple tasks in an application, in C #, thread threads is included in the System.Threading namespace.
One, the simplest way to create a threads is to create a threads instance
eg
Thread myThread = new Thread (new ThreadStart ());
Executive Threads
Mythread.start ();
Use an instance of threads:
Thread myThread = new Thread (new ThreadStart (Incrementer));
Mythread.start ();
Console. Writline ("Execute to this");
public void Incrementer ()
{
for (int i =0;i<1000;i++)
{
Console.WriteLine ("Incrementer: {0}", i);
Thread.Sleep (1000);
}
}
A task that contains this instance is executed in a program, and when Threads.start () is reached, the consloe.writeline operation in the Incrementer operation is performed and the Threads.start () is not resumed until the execution is complete; The following operation, in this instance, outputs "execute to this" to the console.
Note that there is a thread.sleep (1000) in Incrementer, which is the statement that stops this thread for 1 seconds and outputs a WriteLine statement to the console every second. The time in Thread.Sleep () defaults to one millisecond.
The following are very important methods in the Threads class:
Start (): Start thread;
Sleep (int): Static method that pauses the specified number of milliseconds for the current thread;
Abort (): This method is usually used to terminate a thread;
Suspend (): The method does not terminate the unfinished thread, it simply suspends the thread and can be resumed later;
Resume (): Resumes execution of a thread that was suspended by the Suspend () method.
Use an instance of threads:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespacethr{classProgram {Static voidMain (string[] args) {Console.WriteLine ("Start"); Thread Th1=NewThread (THREAD1); Th1. Start (); Console.WriteLine ("Middle"); Thread Th2=NewThread (THREAD2); Th2. Start (); Console.WriteLine ("End"); Thread Th3=NewThread (THREAD3); Th3. Start (); } Public Static voidThread1 () { for(inti =0; I <Ten; i++) Console.WriteLine ("Thread1 exec: {0}", i); } Public Static voidThread2 () { for(intj =0; J <Ten; J + +) Console.WriteLine ("Thread2 exec: {0}", J); } Public Static voidThread3 () { for(intA =0; A <Ten; a++) Console.WriteLine ("Thread3 exec: {0}", a); } }}
The result is:
C # Learning Note thread