C # multi-thread programming

Source: Internet
Author: User

I. Thread Basics

Process: when a program starts to run, it is a process, including the memory and system resources used by the running programs and programs. A process is composed of multiple threads.
Thread: A thread is an execution stream in a program. Each thread has its own proprietary register (Stack pointer, program counter, etc.), but the code zone is shared, that is, different threads can execute the same function (method ).
Multithreading: A program contains multiple execution streams, that is, a program can run multiple different threads to execute different tasks at the same time, that is to say, a single program is allowed to create multiple parallel threads to complete their respective tasks.

Ii. Multithreading
Advantage: it can improve the CPU utilization. In a multi-threaded program, when a thread has to wait, the CPU can run other threads instead of waiting, which greatly improves the program efficiency.
Disadvantage: The thread is also a program, so the thread needs to occupy the memory. The more threads occupy the memory, the more;
Multithreading requires coordination and management, so it requires CPU time to track threads;
Inter-thread access to shared resources will affect each other, and the problem of competing to share resources must be solved;
Too many threads will lead to too complex control, which may lead to many bugs;

 

 

Iii. Classes and methods for controlling threads
Class: using System. Threading; Thread class
Thread class method: Start (): Start Thread;
Sleep (int): a static method that pauses the specified number of milliseconds of the current thread;
Abort (): This method is usually used to terminate a thread;
Suspend (): This method does not terminate the unfinished thread. It only suspends the thread and can be recovered later;
Resume (): Resume the execution of threads suspended by the Suspend () method.
Priority enumeration sets the thread Priority, from high to low Highest, AboveNormal, Normal, BelowNormal, Lowest; The default value is ThreadPriority. Normal.

 

 

 

To instantiate a Thread instance, you need to provide a delegate. The parameter used when instantiating this delegate is the method for the Thread to start in the future. In. NET, two methods are provided to start a thread. One is to start a thread without parameters, and the other is to start a thread with parameters.

1.Startup Mode without Parameters

During large-scale caching, we often use threads. The current program extracts data from the cache and starts another thread to determine whether the current cache data has expired and whether to extract the latest data from the database.

Gender Enumeration

/// <Summary>
/// Name Enumeration
/// </Summary>
Enum PersonSexTypeEnum
{

Man,
Woman,
}

 

Define the Person class and members

Internal class Person
{

/// <Summary>
/// Name
/// </Summary>
Public string Name {get; set ;}

/// <Summary>
/// Age
/// </Summary>
Public int Age {get; set ;}

/// <Summary>
/// Birthday month
/// </Summary>
Public int BirthMonth {get; set ;}

/// <Summary>
/// Gender
/// </Summary>
Public PersonSexTypeEnum sex;

/// <Summary>
/// Person
/// </Summary>
Public Person person {get; set ;}
}

 

Thread

Public class MyThread
{
Static void Main (string [] args)
{

Person p = new Person ();
P. Name = "James ";
P. Age = 22;
P. BirthMonth = 12;
P. sex = PersonSexTypeEnum. Man;
System. Threading. Thread thrad = new System. Threading. Thread (new System. Threading. ThreadStart (p. PersonToString ));
Thrad. Start ();

}
}

In the above example, we instantiate the person class and use the thread thrad to call p. the personToString method. After the execution is completed, the thread ends. do not consider it as calling thrad. abort () abort is to stop the thread. You can see that here you will certainly ask, you instantiate the Person to assign values to all the members of the Person, won't you be able to use it in the thread method? Anyone who has just learned C # knows about it.

/// <Summary>
/// Without Parameters
/// </Summary>
Public void PersonToString ()
{
System. Threading. Thread. Sleep (60 );
Console. WriteLine ("no parameter ");
}

 

2. Here we will introduce the startup method with Parameters

If some parameters need to be included during Thread instantiation, The ThreadStart delegate cannot be used as the constructor parameter to instantiate the Thread, but the parameterizedThreadStart delegate is required, like ThreadStart, it is also the method to be executed when a thread starts. Unlike ThreadStart, it can use a method with object parameters as a constructor parameter during instantiation, the method used for instantiating ThreadStart has no parameters.

 

 

Code

Static void Main (string [] args)
{

Person p = new Person ();
P. Name = "James ";
P. Age = 22;
P. BirthMonth = 12;
P. sex = PersonSexTypeEnum. Man;
// A thread with Parameters
System. Threading. Thread thradparameter = new System. Threading. Thread (new System. Threading. ParameterizedThreadStart (p. PersonToString ));
Thradparameter. Start (p );

}

 

 

Method with Parameters

 

 

Code

/// <Summary>
/// Pass an Object
/// </Summary>
/// <Param name = "obj"> </param>
Public void PersonToString (object obj)
{
If (obj = null)
Return;
If (obj is Person)
{
Person p = obj as Person;
System. Threading. Thread. Sleep (61 );
Console. WriteLine ("person name" + p. Name + "Age" + p. Age );

}
}

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.