C # three methods for passing parameters to multiple threads

Source: Internet
Author: User
Tags mscorlib

 

I learned from C # advanced programming that there are two ways to pass parameters to a Thread. One is to use the Thread constructor with ParameterizedThreadStart to delegate parameters, another way is to create a custom class and define the thread method as an instance method. In this way, you can initialize the instance data and then start the thread.

Method 1: Use ParameterizedThreadStart to delegate

If ParameterizedThreadStart is used, the thread entry must have an object-type parameter and the return type is void. See the following example:

Using System;

Using System. Threading;

 

Namespace ThreadWithParameters

{

Class Program

{

Static void Main (string [] args)

{

String hello = "hello world ";

 

// This can also be abbreviated as Thread thread = new Thread (ThreadMainWithParameters );

// However, to let everyone know that the ParameterizedThreadStart delegate is used here, there is no shorthand

Thread thread = new Thread (new ParameterizedThreadStart (ThreadMainWithParameters ));

Thread. Start (hello );

 

Console. Read ();

}

 

Static void ThreadMainWithParameters (object obj)

{

String str = obj as string;

If (! String. IsNullOrEmpty (str ))

Console. WriteLine ("Running in a thread, received: {0}", str );

}

}

}

 

The trouble here is that the parameters in the ThreadMainWithParameters method must be of the object type, and we need to perform type conversion. Why must the parameter be of the object type? You can see the declaration of the ParameterizedThreadStart delegate.

Public delegate void ParameterizedThreadStart (object obj); // declaration of ParameterizedThreadStart Delegation

Method 2: create a custom class

Define a class, define the required fields in it, and define the main method of the thread as an instance method of the class. If you don't quite understand it, let's look at the actual example.

Using System;

Using System. Threading;

 

Namespace ThreadWithParameters

{

Public class MyThread

{

Private string data;

 

Public MyThread (string data)

{

This. data = data;

}

 

Public void ThreadMain ()

{

Console. WriteLine ("Running in a thread, data: {0}", data );

}

}

 

Class Program

{

Static void Main (string [] args)

{

MyThread myThread = new MyThread ("hello world ");

 

Thread thread = new Thread (myThread. ThreadMain );

Thread. Start ();

 

Console. Read ();

}

}

}

 

I am not very satisfied with this method. I can't create a class as soon as I encounter a time-consuming method...

 

Is there any better way to avoid forced type conversion or creating a new class?

Next I will introduce a method that I accidentally found. Specifically, I don't remember where I met it. It's a sin ..

Method 3: Use the anonymous method

Using System;

Using System. Threading;

 

Namespace ThreadWithParameters

{

Class Program

{

Static void Main (string [] args)

{

String hello = "hello world ";

 

// If it is written as Thread thread = new Thread (ThreadMainWithParameters (hello), an error will be reported during compilation.

Thread thread = new Thread () => ThreadMainWithParameters (hello ));

Thread. Start ();

 

Console. Read ();

}

 

Static void ThreadMainWithParameters (string str)

{

Console. WriteLine ("Running in a thread, received: {0}", str );

}

}

}

 

Wow, you will find that the operation is successful without forced type conversion or new classes.

But why can this approach work? According to yesterday's prompt, I also decompiled it with ildasm, as he said, the third method is actually the same as the second method, but the custom class compiler helps us.

The following is the IL code decompiled by the third method main:

. Method private hidebysig static void Main (string [] args) cel managed

{

. Entrypoint

// Code size 51 (0x33)

. Maxstack 3

. Locals init ([0] class [mscorlib] System. Threading. Thread thread,

[1] class ThreadWithParameters. Program/'<> c _ DisplayClass1 ''CS $ <> 8 _ locals2 ')

IL_0000: newobj instance void ThreadWithParameters. Program/'<> c _ DisplayClass1':. ctor ()

IL_0005: stloc.1

IL_0006: nop

IL_0007: ldloc.1

IL_0008: ldstr "hello world"

 

IL_000d: st1_string ThreadWithParameters. Program/'<> c _ DisplayClass1': hello

IL_0012: ldloc.1

IL_0013: ldftn instance void ThreadWithParameters. Program/'<> c _ DisplayClass1': '<Main> B _ 0 '()

IL_0019: newobj instance void [mscorlib] System. Threading. ThreadStart:. ctor (object,

Native int)

IL_001e: newobj instance void [mscorlib] System. Threading. Thread:. ctor (class [mscorlib] System. Threading. ThreadStart)

IL_0023: stloc.0

IL_0024: ldloc.0

 

IL_0025: callvirt instance void [mscorlib] System. Threading. Thread: Start ()

IL_002a: nop

IL_002b: call int32 [mscorlib] System. Console: Read ()

IL_0030: pop

IL_0031: nop

IL_0032: ret

} // End of method Program: Main

 

Check the IL code in the second method:

. Method private hidebysig static void Main (string [] args) cel managed

{

. Entrypoint

// Code size 44 (0x2c)

. Maxstack 3

. Locals init ([0] class ThreadWithParameters. MyThread myThread,

[1] class [mscorlib] System. Threading. Thread thread)

IL_0000: nop

IL_0001: ldstr "hello world"

IL_0006: newobj instance void ThreadWithParameters. MyThread:. ctor (string)

IL_000b: stloc.0

IL_000c: ldloc.0

 

IL_000d: ldftn instance void ThreadWithParameters. MyThread: ThreadMain ()

IL_0013: newobj instance void [mscorlib] System. Threading. ThreadStart:. ctor (object,

Native int)

IL_0018: newobj instance void [mscorlib] System. Threading. Thread:. ctor (class [mscorlib] System. Threading. ThreadStart)

IL_001d: stloc.1

IL_001e: ldloc.1

 

IL_001f: callvirt instance void [mscorlib] System. Threading. Thread: Start ()

IL_0024: nop

IL_0025: call int32 [mscorlib] System. Console: Read ()

IL_002a: pop

IL_002b: ret

} // End of method Program: Main

 

Comparing the code at both ends, we can find that both of them have a newobj, which serves to initialize an instance of a class. The third method is to generate a class by the compiler: c _ DisplayClass1

IL_0000: newobj instance void ThreadWithParameters. Program/'<> c _ DisplayClass1':. ctor ()

IL_0006: newobj instance void ThreadWithParameters. MyThread:. ctor (string)

 

Note: simplicity is not necessarily a good thing. The anonymous method may cause imperceptible errors. For details, refer to Lao Zhao's article:

Http://www.bkjia.com/kf/201112/113646.html

 

From lexiaoyao20

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.