Thread-Practical Basics (1)

Source: Internet
Author: User
Tags terminates thread class

The main three points: one, task, thread, process, thread concept and relationship two, thread main properties and method three, thread creation, parameter delivery and return value of receive one, task, program, process, thread

What is the task?

Task: The work of the assignment, here refers to the software for a series of operations to achieve a purpose. A task can be a process or a thread, or it can be a simple program.

Multitasking: the ability of the operating system to run multiple applications at once. For example, the current computer can open multiple windows at the same time is a multi-tasking performance.

No longer explained in detail.

What is the program?

Program: An ordered set of instructions, in short, a set of instructions.

No longer explained in detail.

What is the process?

A process is the sum of the program execution Environment .

Explain, this execution environment we can think of it as an operating system for program allocation of the running physical quarantine. In this zone of separation for its allocation of flags ID, memory, CPU and other programs required to run the various resources. The benefit of physical isolation is to prevent other processes from modifying the data of another process. Make the process non-impact.

For a chestnut, I want to make a cake, I have to do a birthday cake recipe, the kitchen has the necessary raw materials (flour eggs god horse), this time I am the processor, recipes is the program, the raw material is input, put the raw material of the kitchen is memory. Process is what I read recipes the sum of the series of processes that bake cakes in the kitchen based on the raw materials taken.

What is a thread?

A thread is a set of instructions that a process runs alone.

To explain, we know that the program code we write is executed from top to bottom with the main () function. A thread is a special object that is part of the operating system's multitasking, which allows parts of the application to run separately against other objects, thus leaving the application's general order of execution.

Take a chestnut and see the code below.

  Public  classClass1 { Public voidTestmain () {task ();//Execute FirstDodata ();//after execution      }       Public voidThreadMain () {thread thread=NewThread (NewThreadStart (Task)); Thread.          Start ();      Dodata (); }       Public voidTask () {}//inside Logic omitted       Public voidDodata () {}//inside Logic omitted         }

Normally it is testmain () This method executes the task first, then executes dodata and must wait until the task method finishes executing the Dodata method.

ThreadMain uses a thread to invoke the task method later, so it can run independently, and Dodata does not have to wait for the task to finish executing.

The relationship between threads and processes

Can be used to represent

Second, understand the thread

Thread building functions, properties, and methods can refer to Msdn:https://msdn.microsoft.com/zh-cn/library/system.threading.thread (v=vs.110). aspx

Here are some of the main things to learn.

To create a thread's constructor:

name description
thread (parameterizedthreadstart)

thread class, specifying a delegate that allows an object to being passed to The thread is started. " > Initializes a new instance of the  thread  class, specifying a delegate that allows an object to be passed to the thread when it is started.

thread (Parameterizedthreadstart, Int32)

thread class, specifying a delegate that allows an object to being passed to the thread when the thread is started and specifying the maximum stack size for the thread. " > Initializes a new instance of the  thread  class, specifying a delegate that allows the object to be passed to the thread when it is started, and specifies the maximum stack size for the thread ...

thread (ThreadStart)

thread class. " > Initializes a new instance of the  thread  class.

Thread(ThreadStart, Int32)

Initializes a new instance of the thread class, specifying the maximum stack size for the threads.

Common Properties for Threads:

  name description
isalive

Gets a value that indicates the execution state of the current thread.

priority

Gets or sets the value that indicates the scheduling priority of the thread.

threadstate

Gets a value that contains the state of the current thread.

Thread Common methods:

is actually the thread that starts, terminates, interrupts, waits, hangs

name Description
Abort()

ThreadAbortException is raised on the thread that called this method to begin the process of terminating this thread. Calling this method usually terminates the thread.

Interrupt()

Interrupts the thread that is in the waitsleepjoin thread state.

Join()

Blocks the calling thread until the thread represented by this instance terminates, while continuing to perform standard COM and SendMessage pump processing.

Join(Int32)

Blocks the calling thread until the thread represented by this instance terminates or passes the specified time, while continuing to perform standard COM and SendMessage message pump processing.

Join(TimeSpan)

Blocks the calling thread until the thread represented by this instance terminates or passes the specified time, while continuing to perform standard COM and SendMessage message pump processing.

ResetAbort()

Cancels the Abort requested by the current thread.

Sleep(Int32)

Suspends the current thread for the specified number of milliseconds.

Sleep(TimeSpan)

Suspends the current thread for the specified time.

Start()

Causes the operating system to change the state of the current instance to ThreadState. Running.

Iii. Creating threads (summary of several methods for creating threads)

(1) No transfer parameters, no return parameters

ThreadStart threadstart=New  ThreadStart (Task); Thread thread=newpublicvoid  Task () {//
The simplified version can be written directly:
Thread thread=new Thread (

Thread. Start ();

(2) passing a single parameter (built with Parameteriizedthreadstart)

Parameterizedthreadstart threadstart=New  parameterizedthreadstart (Calculate) thread thread=  New  thread () thread. Start (0.9publicvoid Task (object  Arg) {  Double diameter=double(ARG);

(3) Pass multiple parameters

The first: Use specialized threading classes.

Put the method called by the thread and the required parameters into a class. The method that is called is the method of the class, and the parameter is the property of the class. Create a constructor with parameters so that parameters can be passed into the properties of the class as parameters of the build function.

 Public  classClass1 { Public voidThreadMain () {MyThread T=NewMyThread (3,4); ThreadStart ThreadStart=NewThreadStart (T.task); Thread Thread=NewThread (ThreadStart); Thread.      Start (); }           }   Public classMyThread { Public DoubleDiameter =Ten;  Public DoubleResult =0;  Public intWidth {Get;Set; }  Public intHeight {Get;Set; }  PublicMyThread (intWidthintheight) {Width=width; Height=height; }       Public voidTask () {intArea = Width *Height; }  }

Second approach: by using delegate delegation

   Public  classClass1 { Public voidThreadMain () {thread thread=NewThread (NewThreadStart (Delegate() {Task (3,4);          })); Thread.      Start (); }        Public voidTask (intWidth,intHeight) {          intArea = Width *Height; }         }   

(4) need to pass parameters and need to return parameters

The method that requires an asynchronous invocation is defined first as a delegate, then invoked asynchronously using BeginInvoke, and the return value is received by EndInvoke.

namespacesx.wf{Delegate intDeletask (intWidth,intHeight);  Public  classClass1 {Staticdeletask task;  Public Static intArea =0;  Public voidThreadMain (intWidth,intHeight) {Task=NewDeletask (Task); Task. BeginInvoke (Width, Height,NewAsyncCallback (taskfinished),NULL); Thread Thread=NewThread (NewThreadStart (Delegate() {Task (Width, Height);})); Thread.      Start (); }        Public Static intTask (intWidth,intHeight) {          intArea = Width *Height; returnArea ; }        Public Static voidtaskfinished (IAsyncResult result) { area=task.       EndInvoke (result); }    }     }

Thread-Practical Basics (1)

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.