先看微软如何给出的方法使用,如下查看,我们发现,如下两个委托,分别对应带参数创建线程 和 不带参数创建线程。
下列 委托 方法不带参数 ThreadStart
{
public class Message
{
public void ShowMessage()
{
string message = string.Format("Async threadId is :{0}",
Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(message);
for (int n = 0; n < 10; n++)
{
Thread.Sleep(300);
Console.WriteLine("The number is:" + n.ToString());
Console.WriteLine("OK!");
}
}
}
//主函数调用时
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main threadId is:" +
Thread.CurrentThread.ManagedThreadId);
Message message = new Message();
//Thread thread = new Thread(message.ShowMessage); //委托绑定 ShowMessage()方法, 下列是通过 ThreadStart 委托绑定, 为什么这么写,后面有介绍
Thread thread = new Thread(new ThreadStart(message.ShowMessage)); //通过ThreadStart委托绑定Message对象的ShowMessage()方法,该句
thread.Start(); //Start() 启动的线程默认在前台执行
Console.WriteLine("Do something ..........!");
Console.WriteLine("Main thread working is complete!");
}
}
}
public class Person
{
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
public class Message
{
public void ShowMessage(object person)
{
if (person != null)
{
Person _person = (Person)person;
string message = string.Format("\n{0}‘s age is {1}!\nAsync threadId is:{2}",
_person.Name, _person.Age, Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(message);
}
for (int n = 0; n < 10; n++)
{
Thread.Sleep(3000);
Console.WriteLine("The number is:" + n.ToString());
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main threadId is:" + Thread.CurrentThread.ManagedThreadId);
Message message = new Message();
//绑定带参数的异步方法
Thread thread = new Thread(new ParameterizedThreadStart(message.ShowMessage));
//Thread thread2 = new Thread((message.ShowMessage));
Person person = new Person();
person.Name = "Jack";
person.Age = 21;
thread.Start(person); //启动异步线程
Console.WriteLine("Do something ..........!");
Console.WriteLine("Main thread working is complete!");
}
}
如上的都能实现如下图的结果:
添加,Thread.Sleep(5000);此时应用程序域将在主线程运行5秒后自动结束
为什么我们可以用 Thread()直接调用方法呢,我们按F12查看 Thread() 微软给出的定义。
如下,Thread 的方法重载,就是调用的 有参数的 和 无参数的 委托
多线程之 ThreadStart 和 ParameterizedThreadStart 委托
原文:http://www.cnblogs.com/imyao/p/5316844.html