C#实现向多线程传参的三种方式实例分析

2019-12-26 14:10:32丽君

 

 
  1. using System;  using System.Threading; 
  2. namespace ThreadWithParameters  { 
  3. class Program  { 
  4. static void Main(string[] args)  { 
  5. string hello = "hello world";  //如果写成Thread thread = new Thread(ThreadMainWithParameters(hello));这种形式,编译时就会报错 
  6. Thread thread = new Thread(() => ThreadMainWithParameters(hello));  thread.Start(); 
  7. Console.Read();  } 
  8. static void ThreadMainWithParameters(string str)  { 
  9. Console.WriteLine("Running in a thread,received: {0}", str);  } 
  10. }  } 

哇,你会发现既不用类型强制转换也不用新建类就运行成功了。

但是为什么这种方式能行呢,根据昨天 @乱舞春秋 的提示,我也用ildasm反编译了一下,确实如他所说,我所谓的第三种方式其实和第二种方式是一样的,只不过自定义类编译器帮我们做了。

下面的是第三种方式main方法反编译的IL代码:

 

 
  1. .method private hidebysig static void Main(string[] args) cil managed  { 
  2. .entrypoint  // 代码大小 51 (0x33) 
  3. .maxstack 3  .locals init ([0] class [mscorlib]System.Threading.Thread thread, 
  4. [1] class ThreadWithParameters.Program/'<>c__DisplayClass1' 'CS#FormatTableID_3#lt;>8__locals2')  IL_0000: newobj instance void ThreadWithParameters.Program/'<>c__DisplayClass1'::.ctor()