C#thread Class multithreaded Series (ii) calling functions with parameters

Source: Internet
Author: User
Tags instance method terminates thread class
first, the thread introduction


In the Windows operating system, each running application is a process, and a process can include one or more threads. A thread is a piece of code that can be executed in parallel in a process, which can occupy the processor time slice independently, and the threads of the same process can share the resources and space allocated by the process. Multi-threaded applications can handle multiple tasks at the same time.



1, Single thread



By default, the system assigns a main thread to the application, which executes the code that starts and ends with the main method, which is the starting entry point for the main thread.



Application.Run (New LoginForm ()); The Run method is used to start a standard application on the current thread and make the specified form visible.



2, multithreading



In general, software that requires user interaction must react to the user's activities as quickly as possible, but at the same time it must perform the necessary calculations to render the data to the user as much as possible, using multithreading at this time.



A single application can also use Multithreading: Communicating with Web servers and databases over a network. Perform an operation that takes a lot of time. Differentiate between tasks that have different priorities. You can use the user interface to quickly respond when assigning time to background tasks.



It is recommended that you do not use too many threads in your program to minimize the use of operating system resources and improve performance. At the same time, tracking a large number of threads takes up a lot of processor time, and using too many threads to control code can produce many bugs.



Second, the basic operation of the thread



C # operates on threads, mainly in the thread class, in the System.Threading namespace, where you can create, pause, resume, hibernate, terminate, and prioritize threads by using the thread class. Alternatively, you can use the Monitor class, the mutex class, and the lock keyword to control synchronous execution of the thread.




1. Thread class



The program code executed by the thread is specified by either the ThreadStart delegate or the Parameterziedthreadstart delegate. During a thread run, different times are in different states, always in one or more states defined by ThreadStart.



Property: CurrentThread: Gets the currently running thread IsAlive: Gets a value indicating the current thread's execution state name: Gets or sets the name of the thread Priority: Gets or sets a value that indicates the scheduling priority of the thread ThreadState: Gets a value that contains the priority of the current thread



Method: Abort: Terminating a thread Join: blocking the calling thread until a thread terminates ResetAbort: cancels the current thread request Abort resum: Resume suspended thread sleep: block the current thread from the specified number of milliseconds Start: causes the thread to be scheduled to execute



2, create the thread



When creating a new thread, you need to use the thread class, a constructor that accepts a ThreadStart delegate or a Parameterizedthreadstart delegate, wrapping a method called by a new thread when the Start method is invoked. After the thread object has been created, it has already been configured, but the actual thread is created, and only the Start method is invoked to actually create the thread.



The Start method is used to cause the thread to be executed, with 2 overloaded forms: public void start () public void Start (object parameter)



Note: A thread has terminated and cannot be restarted by calling the Start method again



3, thread hangs and restores



After you create a thread and start it, you can also suspend, resume, hibernate, or terminate it. The thread hangs and restores primarily invoke the Suspend method of the thread class and the Resume method implementation. Suspend method, which is used to suspend a thread, and the thread does not function after it has been suspended resume method to resume a suspended thread



4. Thread hibernation



Implemented by the Sleep method. Blocks the current thread from the specified time. Thread.Sleep (2000)



5, terminate the thread



Use the Abort method and join method Abort method, terminate the thread, 2 kinds of overload



public void Abort ()



public void Abort (object stateinfo), Stateinfo represents an object that contains specific information



2. Join method to block the calling thread until a thread terminates



public void Join ()



The public void Join (int milliseconds Timeout) waits for the thread to terminate the number of milliseconds, if the thread is terminated, returns True, does not terminate, returns false



The public void Join (TimeSpan timeout) timeout indicates the amount of time to wait for a thread to terminate TimeSpan if terminated, returns True, does not terminate, returns false






several special properties of the ThreadState attribute if we want to be in a multithreaded program until the thread is running, we can use ThreadState to see the running state of the thread.



Aborted: Thread is interrupted. The exception encountered during thread execution was interrupted.



AbortRequested: The thread's Thread.Abort () is invoked but the thread at this point is not stopped.



Background: The thread executes in the background.



Running: The thread is running normally.



Stopped: Thread has been stopped.



Stoprequested: The thread is being asked to stop. There is almost a user request to stop the thread.



Suspended: The thread has been suspended (can be performed by the resume of common methods in thread).



Suspendrequested: The thread is asking to be suspended, and the thread has not been suspended at this time.



Unstarted: Thread has not yet started.



WaitSleepJoin: The thread has invoked the wait (), sleep (), or join () method thread in a blocked state. Iv. Basic usage of the C#thread class



1. Thread class with no parameters

The System.Threading.Thread class allows you to start a new thread and run static or instance methods in the thread stack. A delegate (ThreadStart) that has no parameters and does not return a value (return void) can be passed through the construction method of the thread class, which is defined as follows:

[ComVisibleAttribute (true)]

Public delegate void ThreadStart ()

We can build and run a thread in the following ways.

using system;
using system.collections.generic;
using system.linq;
using system.text;
 
using system.threading; namespace aaaaa {    class program     {         static void main (String[] args)          {            thread th=new  thread (New program ().
Test);             th.
Start ();
            console.readkey ();         }         public  Void test ()//instance method         {             for  (int i = 0; i < 1000; i++)             {    
            console.writeline (i);             }          }    &nbsp}}


Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading;
 
Namespace AAAAA
{
class program
{
static void Main (string[] args)
{

           //thread th=new Thread (new ThreadStart (Test));
            thread th=new thread (Test);             th.
Start ();
            console.readkey ();         }         public  Static void test ()//static method         {             for  (int i = 0; i < 1000 ;  i++)             {    
            console.writeline (i);             }          }    &nbsp}}
2, with a parameter of the thread class


The thread class has an overloaded form of a delegate type with parameters. The definition of this delegate is as follows:
[ComVisibleAttribute (False)]

The code under public delegate void Parameterizedthreadstart (Object obj) uses this delegate with parameters to pass a string argument to the thread:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading;   namespace AAAAA
{
class program
{
static void Main (string[] args)
{
Thread th=new Thread (New Parameterizedthreadstart (Test));

          Thread th=new thread (Test);

Th. Start ("This is a thread class with one parameter.")             "); Console.        Readkey (); The public static void Test (Object obj) {Console.        WriteLine (obj); }    }}  



Output Results:

3, with multiple parameters of the thread class
Since thread defaults to providing only these two constructors, if you need to pass more than one argument, we can use the parameter as the property of the class ourselves. Instantiate the property when defining the object of the class, and then do the operation.


using system;
using system.collections.generic;
using system.linq;
using system.text;
 
using system.threading; namespace aaaaa {    class program     {         static void main (String[] args)          {            person p1=new
 person ();
            p1._name= "Wei";
            p1._age=24;
            p1._sex= ' Male ';             //thread th=new thread (New  threadstart (P1.
SHOWMSG));             thread th=new thread (P1.
SHOWMSG);  &nbSp;          th.
Start ();
            console.readkey ();         }          class 
Person     {        public string _name;
        public int _age;
 
        public char _sex;         public void showmsg ()          {            console.writeline ("
Personal information: \n{0}\n{1}\n{2} ",  _name, _age, _sex);
         }    &nbsp}}


using system;
using system.collections.generic;
using system.linq;
using system.text;
 
using system.threading; namespace aaaaa {    class program     {         static void main (String[] args)          {            thread thread
 = new thread (Test);             thread. isbackground = true;                thread.
Start ();         }         public  Static void test ()         {     
       thread.sleep (3000);         }    &nbsp}} 



If you run the above code, the program waits 3 seconds to exit, and if you remove the annotation and set thread as a background thread, the program exits immediately.

Note that the type of the thread must be set before the Start method is called, otherwise the type cannot be changed if the thread runs.

Threads running through the BeginXxx method are background threads. Are you sure


V. C # Thread class: Two ways to determine whether multiple threads are ending


There are many ways to determine whether all threads have completed their work, if you can adopt a method similar to the object counter, the so-called object counter, that is, an object is referenced once, this counter will add 1, destroy the reference on the minus 1, if the reference number is 0, then the garbage collector will be the reference number of 0 objects to be recycled.

method One: Thread counter

A thread can also use the counter method, that is, for all the threads that need to be monitored, set a thread counter, start a thread, add 1 for this counter in the thread's execution method, and subtract 1 for this counter if a thread finishes (the end of the thread execution method is minus 1 for this counter). Then start a thread and monitor the counter at a certain interval, as the brown counter is 0, indicating that all threads are finished. Of course, you can also not use this monitoring thread, but at the end of each worker thread (after the code for the counter minus 1) To monitor this counter, that is, each worker thread before exiting, but also responsible for detecting this counter. Use this method do not forget to sync this counter variable ah, otherwise it will have unintended consequences.

method Two: Using the Thread.Join method

The join method continues to execute the following statement only when the thread ends. It is possible to call its join method on each thread, but note that the call is to be in another thread, not the main thread, or the program will be blocked.

above is a few superficial ideas that I have thought about and summed up in my actual study. In short, I think, to become a qualified programmer need to have more conditions, will think, learn, will be hands-on is the most basic requirements. In the actual work, but also often understand the industry dynamics, active their own thinking, rather than behind closed doors, sealed their own thoughts. Regular learning can make it less likely to lose course in this fast-changing IT industry to qualify as a qualified programmer and move on to a good programmer. Hope that this knowledge can help more people. 



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.