Multi-thread thread class in C #

Source: Internet
Author: User
Use the System.Threading.Thread class to create and control threads.

Common constructor functions are:

        Summary:     Initializes a new instance of the System.Threading.Thread class, specifying a delegate that allows an object to be passed to the thread when it is started. Parameters://   start://     System.Threading.ParameterizedThreadStart Delegate, which represents the method to invoke when this thread starts execution. Exception://   system.argumentnullexception://     start is null.        [Securitysafecritical]public Thread (Parameterizedthreadstart start);////Summary://     initialization A new instance of the System.Threading.Thread class. Parameters://   start://     System.Threading.ThreadStart Delegate, which represents the method to invoke when this thread starts execution. Exception://   system.argumentnullexception://     start parameter is null.        [Securitysafecritical]public Thread (ThreadStart start);

1. Create threads without parameters

The ThreadStart delegate defines a parameterless method that returns the type bit void.

        public void Main ()        {            Thread vthread = new Thread (threadfun);//vthread.name = "Td_name";  Thread name Vthread.start (); Start 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 <; i++)            {                Console.Write (".");                Thread.Sleep (+);            }            Console.WriteLine ("THREAD END");        }

Output Result:

Replacing the Threadfun () in the appeal code with a lambda expression becomes a simple way to use the thread:

        public void Main ()        {            Thread vthread = new Thread (() =>{                Console.WriteLine ("Running in a new Thread");}); /vthread.name = "Td_name";  Thread name Vthread.start (); Start execution Thread Console.WriteLine ("This is the main thread");        }

2. Passing parameters to threads

Two ways: one is to construct the thread using the method parameter with Parameterizedthreadstart delegate , and the other is to create a custom class that defines the thread's method as an instance method. This initializes the data for the instance before starting the thread.

such as: passing parameters

        public struct Tddata//pass 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 execution thread, pass parameter Console.WriteLine ("This is the main thread");        } void Threadfun (Object POBJ)//From Delegate: Parameterizedthreadstart         {            tddata vData = (tddata) pObj;            Console.WriteLine ("In a new thread, received:{0}", Vdata.message);                    }

Use the second way: first customize 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, the thread is created in the main thread (where needed) and the instance method Tdhelper.threadfun () is used as the argument for the constructor.

        public void Main ()        {            Tddata tdata = new Tddata () {Message = "Thread Info"};            Tdhelper thelper = new Tdhelper (tdata); Pass parameter thread vthread = new Thread (thelper.threadfun);            Vthread.start ();            Console.WriteLine ("This is the main thread");        }

3. Background Threads

By default, the thread class creates threads on the pre-platform thread, and threads in the thread pool are always background threads. As long as there is a foreground thread running, the application process is running, and if multiple foreground threads are running, and the main () method ends, the application remains active until all foreground threads complete the task.

You can make it a background thread by setting the IsBackground property of the thread class instance;

        public void Main ()        {            Thread vthread = new Thread (() =>{                Console.WriteLine ("New Thread Started");  Title3thread.sleep (the);                Console.WriteLine ("New thread completed"); Title2});//vthread.isbackground = true;            Vthread.start ();            Console.WriteLine ("This is the main thread"); Title1}

When the IsBackground property defaults to False , you can see 3 output messages in the console completely, but if you set it to True , you do not wait until the 3rd message (Title2 ) output, the main thread main () has finished executing and the console window is automatically closed.

4. Priority of Threads

The Priority property allows you to adjust the precedence of the thread class instance by default: Vthread.priority = Threadpriority.normal; Enumeration values

Relationship: Highest > AboveNormal > Normal > BelowNormal > Lowest

5. Control threads

You can create a thread by calling the start () method of the Thread object. However, after the start () method is called, the new thread is still not in the Running state, but the unstarted state. Only the thread scheduler of the operating system chooses to run the thread, and the thread changes to the Running state. The current state of the thread can be obtained through the Thread.threadstate property.

Using the Thread.Sleep () method causes the thread to be in the WaitSleepJoin state, and after the time period defined by the Sleep () method is passed, the thread waits for the operating system to be dispatched again.

To stop a thread, you can call the Thread.Abort () method. Calling this method throws a ThreadAbortException in the thread that receives the terminating command, catches the exception with a handler, and the thread can do some cleanup before the end. The thread can also continue to work after receiving the result of the call to the Thread.Abort () method ThreadAbortException exception. If the thread does not have a reset termination, the state of the thread receiving the termination request is changed from abortrequested to aborted.

If you want to wait for the thread to end, you can call the Thread.Join () method, which stops the current thread and sets it to the WaitSleepJoin state until the joined thread finishes.

See:

[]

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.