C # thread ThreadStart and Parameterizedthreadstart

Source: Internet
Author: User

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. 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, as in the following code:

View Code

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Threading;

Namespace Startthread
{
Class Program
{
int interval = 200;
static void Main (string[] args)
{
Program P = new program ();
Thread nonparameterthread = new Thread (new ThreadStart (P.nonparameterrun));
Nonparameterthread.start ();
}
<summary>
Start method without parameters
</summary>
public void Nonparameterrun ()
{
for (int i = 0; i <; i++)
{
Console.WriteLine ("System Current time millisecond value:" +datetime.now.millisecond.tostring ());
Thread.Sleep (interval);//Let thread pause
}
}
}

The running effect of the program we do not need to run and will know, that is, in the loop of the system current time of the millisecond part of the output, after each output will be the current thread paused, until 10 times after the completion of the execution of the termination of the thread.
In the above code, we specify the thread pause interval by defining the global variables, in this way, if you want to run 10 threads, each thread's pause interval is different, you need to define 10 global variables, although ultimately does not affect the performance of the system, but always feel not too good.
Is there a more simple way? Yes! That is, using a startup method with parameters.
Start-up method with parameters
If you want to take some arguments when you instantiate a thread, you cannot instantiate the thread with the ThreadStart delegate as the argument to the constructor, but to parameterizedthreadstart the delegate, As with ThreadStart, it is also the method to be executed when the thread starts, and unlike ThreadStart, it can be instantiated with a method with an object parameter as the constructor parameter. The method used to instantiate the ThreadStart is not a 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.
Here is an example where the thread's pause interval is specified when the thread is started, with the following code:

view code

using System;
Using System.Collections.Generic;
using System.Text;
using System.Threading;

Namespace Startthread
{
Class program
{
int interval = $;
static void Main (string[] args)
{
Program P = new program ();

Thread parameterthread = new Thread (new Parameterizedthreadstart (P.parameterrun));
Parameterthread.name = "Thread A:";
Parameterthread.start (30);
}

///<summary>
//Start method with parameters
//</summary>
//<param name= "MS" > Hibernate during running of threads Interval </param>
public void Parameterrun (object ms)
{
Int j = ten;
Int. TryParse (Ms. ToString (), out j);//The TryParse method is used here to avoid an exception that cannot be converted
for (int i = 0; i <; i++)
{
Console.WriteLine (thread.cu Rrentthread.name+ "System Current time millisecond value:" + DateTime.Now.Millisecond.ToString ());
Thread.Sleep (j);//Leave thread paused
}
}
}
}

In this method, we specify the thread's pause interval when the thread is started, which is the phrase:
Parameterthread.start (30);
The method that runs when the thread starts is public void Parameterrun (object ms), and the int type variable with the value 30 is boxed as object, so it needs to be converted to an int type in the method, which can be solved by unpacking or other means.
If we want to start two threads, each thread has a different pause interval, the boot code is as follows:

  

View Code

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Threading;

Namespace Startthread
{
Class Program
{
int interval = 200;
static void Main (string[] args)
{
Program P = new program ();

Thread parameterthread = new Thread (new Parameterizedthreadstart (P.parameterrun));
Parameterthread.name = "Thread A:";
Parameterthread.start (30);
Start a second thread
Parameterthread = new Thread (new Parameterizedthreadstart (P.parameterrun));
Parameterthread.name = "Thread B:";
Parameterthread.start (60);
}

<summary>
Start-up method with parameters
</summary>
<param name= "MS" > Hibernate interval to let threads run in the process </param>
public void Parameterrun (object ms)
{
int j = 10;
Int. TryParse (Ms. ToString (), out j);//The TryParse method is used here to avoid exceptions when the conversion is not possible
for (int i = 0; i <; i++)
{
Console.WriteLine (thread.currentthread.name+ "System Current time millisecond value:" + DateTime.Now.Millisecond.ToString ());
Thread.Sleep (j);//Let thread pause
}
}
}
}

To make a point of the above code, that is, after the thread is started, the instance of the thread does not have to exist again, for example, in the above code I used the same instance to instantiate two threads, and these two threads run normally.
Continue to explore
The above solves a problem, if you need to start the thread to solve the problem, if the above problems continue to explore, such as: When starting a thread not only to specify the thread pause interval, but also need to specify the number of cycles (in all the above examples are executed 10 times), how to solve this problem?
There are two ways to solve this:
First, you can continue to make a fuss here at Parameterizedthreadstart, because you can use an object type parameter, which can be resolved by an array or a class (because they are subclasses of object). I did use arrays to handle this when I was working on a system, which required that the use of each parameter in the array must be clearly known in the thread initiation method, not too convenient.
Here's how to redefine an entity class to resolve the code below.

View Code

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Threading;

Namespace Startthread
{
Class Mythreadparameter
{
private int interval;
private int loopcount;
<summary>
Number of Cycles
</summary>
public int Loopcount
{
get {return loopcount;}
}

<summary>
Pause interval for threads
</summary>
public int Interval
{
get {return interval;}
}
<summary>
constructor function
</summary>
<param name= "Interval" > Thread pause Interval </param>
<param name= "Loopcount" > Cycle times </param>
Public mythreadparameter (int interval,int loopcount)
{
This.interval = interval;
This.loopcount = Loopcount;
}
}
Class Program
{
int interval = 200;
static void Main (string[] args)
{
Program P = new program ();

Thread parameterthread = new Thread (new Parameterizedthreadstart (P.myparameterrun));
Parameterthread.name = "Thread A:";
Mythreadparameter paramter = new Mythreadparameter (50, 20);
Parameterthread.start (paramter);
}


<summary>
Start-up method with multiple parameters
</summary>
<param name= "MS" > method Parameters </param>
public void Myparameterrun (object ms)
{
Mythreadparameter parameter = ms as mythreadparameter;//type conversion
if (parameter! = NULL)
{
for (int i = 0; i < parameter. Loopcount; i++)
{
Console.WriteLine (Thread.CurrentThread.Name + "system Current time millisecond value:" + DateTime.Now.Millisecond.ToString ());
Thread.Sleep (parameter. Interval);//Let thread pause
}
}
}
}
}

The second approach is somewhat similar to the above approach, as well as the need to introduce an external class, and place the thread instance in the introduced class, which is suitable for situations where the business logic is more complex to process in a thread. I've used this in a project I've been working on for a long time, and it's used for bidirectional data transfer.
If you implement the above effect, the code is as follows:

  

View Code

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Threading;

Namespace Startthread
{
Class Mythreadparameter
{
private int interval;
private int loopcount;
private thread thread;

<summary>
constructor function
</summary>
<param name= "Interval" > Thread pause Interval </param>
<param name= "Loopcount" > Cycle times </param>
Public mythreadparameter (int interval,int loopcount)
{
This.interval = interval;
This.loopcount = Loopcount;
thread = new Thread (new ThreadStart (Run));
}

public void Start ()
{
if (thread! = NULL)
{
Thread. Start ();
}
}

private void Run ()
{
for (int i = 0; i < Loopcount; i++)
{
Console.WriteLine ("System Current time millisecond value:" + DateTime.Now.Millisecond.ToString ());
Thread.Sleep (interval);//Let thread pause
}
}
}
Class Program
{
static void Main (string[] args)
{
Mythreadparameter parameterthread = new Mythreadparameter (30, 50);
Parameterthread.start ();
}

}
}

The above code runs in a similar way to the previous code, except that the business processing code is placed in a separate class mythreadparameter, making mythreadparameter look like a thread, Actually maintaining the thread inside of it, the benefits of doing so in some large systems are easy to maintain.
Summary: In this article is mainly about how to start the thread of the problem, at startup may encounter the need for parameters, require multiple parameters, here is how to solve these problems ideas. There is a huge class library in the. NET class library, but there is not always a suitable class to solve the problems we encounter, but we always think of the right way.

C # thread ThreadStart and Parameterizedthreadstart

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.