C # Multi-threading and delegation

Source: Internet
Author: User

One: Thread
There are two ways to start a thread in. NET, one is to start without parameters, and the other is to start with a parameter.
How to start without parameters
If no additional information is required to start the parameter, you can use ThreadStart to instantiate the thread:
Start-up method with parameters

With parameters, it is not possible to instantiate the thread with the ThreadStart delegate as the argument to the constructor, and to Parameterizedthreadstart the delegate, like ThreadStart, it is also the method to be executed when the thread starts. Unlike ThreadStart, it can be instantiated with a method with an object parameter as the constructor parameter, and the method used to instantiate the ThreadStart is no parameter. Why is an object such a parameter? is simple, because object in. NET is the base class for all types, which can be used to represent an array (array), Interface (interface), ValueType (value type, such as Bool,byte,char,short,int,float,long, Double, etc.), Class (Class), and other types in. Net. Of course, this also means that if you want to start a thread and pass an int type argument to it, you must make the appropriate type conversion in the Startup method.
This parameter of type object can be defined as a class with multiple attributes, or a string separated by $, used to decompose an array to use
Simple Instance Code:

With no parametersThreadStartTs= New ThreadStart(ThreadFunc);ThreadT= New Thread(Ts);T.Start();With parametersParameterizedthreadstart Parstart = new parameterizedthreadstart ( goto); thread MyThread = new thread (parstart object o = (object) txt_url.< Span class= "Typ" >text;. Starto         

Detailed Instance code:

ProgramP= New Program();ThreadNonparameterthread= New Thread(New ThreadStart(P.Nonparameterrun));Nonparameterthread.Start();ThreadParameterthread= New Thread(New Parameterizedthreadstart(P.Parameterrun));Parameterthread.Name = "Thread A:";Parameterthread.Start(30);<summary>Start method without parameters</summary>Public void Nonparameterrun(){For (IntI= 0;I< 10;I++) {Console.WriteLine("System Current time millisecond value:"+Datetime.Now.Millisecond.Tostring());Thread.Sleep(200);To suspend a thread}} <summary>Start-up method with parameters</summary><param name= "MS" > Hibernate interval to let threads run in the process </param>Public void Parameterrun(ObjectMs){IntJ= 10; Int.TryParse(Ms.Tostring(), OutJ);The TryParse method is used here to avoid exceptions when the conversion is not possible.For (IntI= 0;I< 10;I++){Console.WriteLine(Thread.CurrentThread.Name+ + datetime. Now. Millisecond. Tostring                                 thread. Sleepj Let thread pause                          }                 }   

Two: Commission
A delegate is a method of passing in the form of a parameter.

Private Static void Writestrtofile(StringTxt){Write(Txt}private  void writestrtofiledelegate< Span class= "pun" > (string Txt Define delegate new writestrtofiledelegatewritestrtofile Begininvoke (txt, null , null);  Use delegates asynchronously                 

One more example:

Public Delegate void Greetingdelegate(StringName);Defining delegatesDefine two methodsPrivate Static void Englishgreeting(StringName) {Console.writeline (  + Name); }private  void chinesegreeting  (string Name)  { console. Writeline ( "Good morning,"  + Name}             /span>                

Use:

Private Static void Greetpeople(StringName, greetingdelegate makegreeting)  {  makegreeting ( name); //here the default synchronization mode, the same as the Makegreeting.invoke (name) effect } //use greetpeople ( span class= "str" > "Jimmy Zhang" , englishgreeting greetpeople ( "Zhang Ziyang" ,< Span class= "PLN" > chinesegreeting        

In fact, we can also bypass the Greetpeople method and directly invoke Englishgreeting and chinesegreeting:  through delegates;

greetingdelegate delegate1< Span class= "pun" >;  delegate1 = englishgreeting  //assign a value to a delegate type first  delegate1 +=  chinesegreeting; //to bind this delegate variable again a method  //will successively call Englishgreeting and Chinesegreeting method  Span class= "PLN" > delegate1  (console. Readkey             


The Invoke method of the delegate is used for synchronous invocation. A synchronous call can also be called a blocking call, which blocks the current thread and then executes the call, and then continues down after the call is complete. Synchronous calls can block threads, and if you are invoking a heavy workload (such as a large number of IO operations), it can cause the program to pause for a long time, creating a bad user experience, which is necessary for an asynchronous invocation.
Instead of blocking the thread, the asynchronous call plugs the call into the thread pool, which the program's main thread or UI thread can continue to execute.
The asynchronous invocation of a delegate is implemented by BeginInvoke and EndInvoke.

Comparison:
In instantiating an instance of the thread, you need to provide a delegate that is used when instantiating the delegate to be the method that the thread will run when it starts.

A delegate is actually a thread

MethodInvoker=newmethodinvoker(dopay);  Defines the delegate this .  BeginInvoke(mi);            


Here MethodInvoker
Just a delegate, we can assume that all delegates with no parameters of the return value of void are the same as methodinvoker, and that they can delegate to a method that has no arguments for the return value of void.

You write yourself a public Delegate Sub ABC, and this time ABC and MethodInvoker are exactly the same. So. Net provides this just to make it easier for you to write, save yourself a lot of the same commission.

C # Multi-threading and delegation (GO)

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.