sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  1796 随笔 :: 22 文章 :: 24 评论 :: 226万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

https://www.cnblogs.com/qixuejia/archive/2015/02/09/4281079.html

ThreadStart:

ThreadStart这个委托定义为void ThreadStart(),也就是说,所执行的方法不能有参数。

ThreadStart threadStart=new ThreadStart(Calculate);
Thread thread=new Thread(threadStart);
thread.Start();
public void Calculate()
   {
 double Diameter=0.5;
 Console.Write("The Area Of Circle with a Diameter of {0} is {1}"Diameter,Diameter*Math.PI);
   }

       这里我们用定义了一个ThreadStart类型的委托,这个委托制定了线程需要执行的方法: Calculate,在这个方法里计算了一个直径为0.5的圆的周长,并输出.这就构成了最简单的多线程的例子,在很多情况下这就够用了


 

ParameterThreadStart:

ParameterThreadStart的定义为void ParameterizedThreadStart(object state),使用这个这个委托定义的线程的启动函数可以接受一个输入参数,具体例子如下 :

 

ParameterizedThreadStart threadStart=new ParameterizedThreadStart(Calculate)
Thread thread=new Thread() ;
thread.Start(0.9);
public void Calculate(object arg)
{
double Diameter=double(arg);
Console.Write("The Area Of Circle with a Diameter of {0} is {1}"Diameter,Diameter*Math.PI);
}


Calculate方法有一个为object类型的参数,虽然只有一个参数,而且还是object类型的,使用的时候尚需要类型转换,但是好在可以有参数了,并且通过把多个参数组合到一个类中,然后把这个类的实例作为参数传递,就可以实现多个参数传递.比如:

 

 

public AddParams(int numb1, int numb2)
{
  a = numb1;
  b = numb2;
}
  AddParams ap = new AddParams(10, 10);
  Thread t = new Thread(new ParameterizedThreadStart(Add));
  t.Start(ap);
  Console.ReadLine();
}

#region Add method
static void Add(object data)
{
  if (data is AddParams)
  {
    Console.WriteLine("ID of thread in Main(): {0}",
      Thread.CurrentThread.ManagedThreadId);

    AddParams ap = (AddParams)data;
    Console.WriteLine("{0} + {1} is {2}",
      ap.a, ap.b, ap.a + ap.b);
  }
}
#endregion


 


posted on   sunny123456  阅读(335)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示