C # Thread class with multiple threads,

Source: Internet
Author: User

C # Thread class with multiple threads,

You can use the System. Threading. Thread class to create and control threads.

Common constructors include:

// Abstract: // initialize a new instance of the System. Threading. Thread class, specifying the delegate that allows the object to be passed to the Thread when the Thread starts. //// Parameter: // start: // System. Threading. ParameterizedThreadStart delegate, which indicates the method to be called when the thread starts execution. //// Exception: // System. ArgumentNullException: // start is null. [SecuritySafeCritical] public Thread (ParameterizedThreadStart start); // Summary: // initialize a new instance of the System. Threading. Thread class. //// Parameter: // start: // System. Threading. ThreadStart delegate, which indicates the method to be called when the thread starts execution. //// Exception: // System. ArgumentNullException: // The start parameter is null. [SecuritySafeCritical] public Thread (ThreadStart start );

1. No parameter creation thread

The ThreadStart delegate defines a non-parameter method that returns the type bit void.

Public void Main () {Thread vThread = new Thread (ThreadFun); // vThread. name = "td_Name"; // thread Name vThread. start (); // Start the execution thread Console. writeLine ("This is the main thread: id =" + Thread. currentThread. managedThreadId);} void ThreadFun () // from delegate: ThreadStart {Console. writeLine ("Running in a new thread: id =" + Thread. currentThread. managedThreadId); for (int I = 0; I <10; I ++) {Console. write (". "); Thread. sleep (500);} Console. writeLine ("thread end ");}

Output result:

Replace ThreadFun () in the appeal code with a Lambda expression to make it easy to use Thread:

Public void Main () {Thread vThread = new Thread () => {Console. writeLine ("Running in a new thread") ;}); // vThread. name = "td_Name"; // thread Name vThread. start (); // Start the execution thread Console. writeLine ("This is the main thread ");}

 

2. Passing parameters to the thread

Two Methods: one is to use the method parameter with ParameterizedThreadStart to construct the Thread; the other is to create a custom class and define the Thread method as an instance method, in this way, the instance data is first initialized in the startup thread.

For example, passing Parameters

Public struct TdData // transmit data {public string Message; // data string field}

Use the first method:

Public void Main () {TdData tData = new TdData () {Message = "Thread Info"}; Thread vThread = new Thread (ThreadFun); vThread. start (tData); // Start the execution thread and pass the Console parameter. writeLine ("This is the main thread");} void ThreadFun (object pObj) // delegate: ParameterizedThreadStart {TdData vData = (TdData) pObj; Console. writeLine ("In a new thread, Received: {0}", vData. message );}

Use the second method: first define a class.

Public class TdHelper {public TdData mData; // pass data // constructor public TdHelper (TdData pData) {this. mData = pData;} public void ThreadFun () // from delegate: ThreadStart {Console. writeLine ("In a new thread, TdDataMessage: {0}", mData. message );}}

Then, create a Thread in the main Thread (where needed) and use the instance method TdHelper. ThreadFun () as the constructor parameter.

Public void Main () {TdData tData = new TdData () {Message = "Thread Info"}; TdHelper tHelper = new TdHelper (tData ); // pass the parameter Thread vThread = new Thread (tHelper. threadFun); vThread. start (); Console. writeLine ("This is the main thread ");}

 

3. Background thread

By default, threads created by the Thread class are frontend threads, and threads in the Thread pool are always background threads. As long as one front-end thread is running, the application process is running. If multiple Front-End threads are running and the Main () method is finished, the application is still active, until all foreground threads complete the task.

You can set the IsBackground attribute of the Thread class instance to make it a background Thread;

        public void Main()        {            Thread vThread = new Thread(() =>            {                Console.WriteLine("New thread started");  // Title3                Thread.Sleep(5000);                Console.WriteLine("New thread completed"); // Title2            });            //vThread.IsBackground = true;            vThread.Start();            Console.WriteLine("This is the main thread"); // Title1        }

 

When the default IsBackground attribute is false, three output statements can be fully viewed on the console. However, if the IsBackground attribute is set to true, the output may not be less than 3rd messages (Title2, the Main thread Main () has been executed, and the console window is automatically closed.

4. thread priority

The Priority attribute allows you to adjust the Priority of a Thread-class instance. The default value is vThread. Priority = ThreadPriority. Normal. // enumeration value.

Link: Highest> AboveNormal> Normal> BelowNormal> Lowest

5. Control thread

Call the Start () method of the Thread object to create a Thread. However, after the Start () method is called, The New thread is not in the Running state, but Unstarted state. Only when the thread scheduler of the operating system selects to run this thread will the thread change to the Running state. The current state of the Thread can be obtained through the Thread. ThreadState attribute.

Using the Thread. Sleep () method puts the Thread in the WaitSleepJoin state. After the time period defined by the Sleep () method, the Thread will wait for the Thread to be scheduled again by the operating system.

To stop a Thread, you can call the Thread. Abort () method. When this method is called, a ThreadAbortException will be thrown in the thread that receives the termination command. A handler can capture this exception and the thread can complete some cleanup before the end. The Thread can continue working after receiving the result ThreadAbortException that calls the Thread. Abort () method. If the thread has not been reset to terminate, the status of the thread that receives the terminate request is changed from AbortRequested to Aborted.

If you want to wait for the Thread to end, you can call the Thread. Join () method. It will stop the current Thread and set it to the WaitSleepJoin State until the added Thread is complete.

 

[Http://www.cnblogs.com/CUIT-DX037/]

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.