C # Multiple threads and delegates

Source: Internet
Author: User
One: Thread
There are two ways to start a thread in. NET, one that starts without parameters, and the other is the way that you start with parameters.
Start with no parameters
If you do not need additional information to start the parameter, you can use ThreadStart to instantiate the thread:
Startup method with Parameters

With parameters, you cannot instantiate thread with the ThreadStart delegate as a parameter to the constructor, but to parameterizedthreadstart the delegate, as with ThreadStart, it is also the method to execute when the thread starts. Unlike ThreadStart, it can be instantiated with a method with an object parameter as the parameter of the constructor, and the method used to instantiate the ThreadStart is without parameters. Why is it such an argument as object? is simple, because object is a base class for all types in. NET, and it can be used to represent array (array), Interface (interface), valuetype (value type, such as Bool,byte,char,short,int,float,long, Double), Class (Class), and so on. NET type. Of course, this also means that if you want to start a thread and pass an int type parameter to it, you must do the corresponding type conversion in the Startup method.
This type of object parameter can define a class with multiple attributes, or a string separated by $, that is used to decompose an array
Simple Instance Code:
ThreadStart ts = new ThreadStart (threadfunc) with no parameters;
Thread t = new thread (TS);
T.start ();

With parameter 
parameterizedthreadstart parstart = new Parameterizedthreadstart (GoTo);
Thread mythread = new Thread (parstart);
Object o = (object) Txt_url. Text;
Mythread.start (o);
Detailed Instance code:
Program P = new program ();
 thread nonparameterthread = new Thread (new ThreadStart (P.nonparameterrun));

 nonparameterthread.start ();
 thread parameterthread = new Thread (new Parameterizedthreadstart (P.parameterrun));
 parameterthread.name = "Thread A:";
 parameterthread.start (30);                                   /// <summary>                  ///with no parameters the Start method         & nbsp        ///</summary>                  public void Nonparameterrun ()                  {          &NBSP ;              for (int i = 0; i < i++)                          {      &NBSp                          console.writeline ("System Current time millisecond value:" +d
AteTime.Now.Millisecond.ToString ());                                  thre Ad. Sleep (200)//Let thread pause                         &NBSP}   &nbs P                            ///<summary> & nbsp                ///with parameter startup method               &NBSP ;  ///</summary>                  ///<param name= "MS" > Let Threads Run Process Hibernate interval </param>                  public void Parameterrun (object ms) & nbsp                {                        int j = 10;                          int. TryParse (Ms. ToString (), out j);//Here The TryParse method is used to avoid exceptions when not convertible                     &NB Sp    for (int i = 0; i < i++)                          {                              &N Bsp
 console.writeline (thread.currentthread.name+ "System Current time millisecond value:" + DateTime.Now.Millisecond.ToString ());                                  thre Ad.  Sleep (j);//Let thread pause                          }                  
II: Commissioned
A delegate is a method of passing in the form of parameters.
private static void Writestrtofile (String txt)
{
write (TXT);
}
Private delegate void Writestrtofiledelegate (string txt);//define Delegate
new Writestrtofiledelegate (Writestrtofile). BeginInvoke (TXT, null, NULL);//asynchronous use of Delegates
Let me cite one more example:
public delegate void Greetingdelegate (string name);//define

two methods
private static void Englishgreeting (string Name) 
{
Console.WriteLine ("Morning," + name);
}

private static void Chinesegreeting (string name) {
Console.WriteLine ("Good Morning," + name);
}
Use:
private static void Greetpeople (string name, Greetingdelegate makegreeting) 
{
makegreeting (name);//This is the default synchronization method, Same as the Makegreeting.invoke (name) effect
}

//Use
greetpeople ("Jimmy Zhang", englishgreeting);
Greetpeople ("Zhang Ziyang", chinesegreeting);
In fact, we can also bypass the Greetpeople method by delegating direct calls to Englishgreeting and chinesegreeting:
Greetingdelegate delegate1;
Delegate1 = englishgreeting; Assign a variable of a delegate type
delegate1 + = chinesegreeting//To bind a method to this delegate variable
//will successively invoke the Englishgreeting and chinesegreeting method 
   delegate1 ("Jimmy Zhang");

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 downward after the call completes. Synchronous calls block threads, and asynchronous calls are necessary if they are to invoke a heavy workload, such as a large number of IO operations, which may cause the program to pause for a long time, causing a bad user experience.
Instead of blocking the thread, the asynchronous call plugs the call into the thread pool, and the program's main thread or UI threads can continue to execute.
Asynchronous invocations of delegates are implemented through BeginInvoke and EndInvoke.

Comparison:
In instantiating an instance of thread, you need to provide a delegate, and the parameters used to instantiate the delegate are the methods that the thread will run when it is started.

A delegate is actually a thread


MethodInvoker mi = new MethodInvoker (dopay);//define delegate this
. BeginInvoke (MI);


Here MethodInvoker
is just a delegate, and we can assume that all delegates with void return values of NULL are the same as methodinvoker, and they can all delegate to a method that has no parameters whose return value is void.

You write yourself a public Delegate Sub ABC, at which point ABC and MethodInvoker are exactly the same. So. Net provides this only to facilitate your writing, save yourself to write a bunch of the same delegate.

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.