免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 958 | 回复: 0

C#中ParameterizedThreadStart和ThreadStart区别 [复制链接]

论坛徽章:
0
发表于 2011-12-20 09:44 |显示全部楼层
C#中ParameterizedThreadStart和ThreadStart区别

不需要传递参数,也不需要返回参数

  我们知道启动一个线程最直观的办法是使用Thread类,具体步骤如下:

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的圆的周长,并输出.这就构成了最简单的多线程的例子,在很多情况下这就够用了,然后 ThreadStart这个委托定义为void ThreadStart(),也就是说,所执行的方法不能有参数,这显然是个很大的不足,为了弥补这个缺陷,聪明的程序员想出了许多好的方法,我们将在需要传递多个参数一节中进行介绍,这里我们先介绍.Net为了解决这个问题而设定的另外一个委托:就是ParameterizedThreadStart ,我会在下面详细讲述。

  需要传递单个参数

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类型的,使用的时候尚需要类型转换,但是好在可以有参数了,并且通过把多个参数组合到一个类中,然后把这个类的实例作为参数传递,就可以实现多个参数传递.比如:

class AddParams
{
    public int a, b;

    public AddParams(int numb1, int numb2)
    {
      a = numb1;
      b = numb2;
    }
}
#endregion

class Program
{
    static void Main(string[] args)
    {
      Console.WriteLine("***** Adding with Thread objects *****");
      Console.WriteLine("ID of thread in Main(): {0}",
        Thread.CurrentThread.ManagedThreadId);

      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
}
}

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP