本文主要介绍了c#使用多线程的几种方式,通过示例学习c#的多线程使用方式,大家参考使用吧
(1)不需要传递参数,也不需要返回参数
ThreadStart是一个委托,这个委托的定义为void ThreadStart(),没有参数与返回值。
代码如下:
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 30; i++)
{
ThreadStart threadStart = new ThreadStart(Calculate);
Thread thread = new Thread(threadStart);
thread.Start();
}
Thread.Sleep(2000);
Console.Read();
}
public static void Calculate()
{
DateTime time = DateTime.Now;//得到当前时间
Random ra = new Random();//随机数对象
Thread.Sleep(ra.Next(10,100));//随机休眠一段时间
Console.WriteLine(time.Minute + ":" + time.Millisecond);
}
}
(2)需要传递单个参数
ParameterThreadStart委托定义为void ParameterizedThreadStart(object state),有一个参数但是没有返回值。
代码如下:
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 30; i++)
{
ParameterizedThreadStart tStart = new ParameterizedThreadStart(Calculate);
Thread thread = new Thread(tStart);
thread.Start(i*10+10);//传递参数
}
Thread.Sleep(2000);
Console.Read();
}
public static void Calculate(object arg)
{
Random ra = new Random();//随机数对象
Thread.Sleep(ra.Next(10, 100));//随机休眠一段时间
Console.WriteLine(arg);
}
}
(3)使用专门的线程类(常用)
使用线程类可以有多个参数与多个返回值,十分灵活!
代码如下:
class Program
{
static void Main(string[] args)
{
MyThread mt = new