C#线程系列讲座(2):Thread类的应用2011-05-08一、Thread类的基本用法通过System.Threading.Thread类可以开始新 的线程,并在线程堆栈中运行静态或实例方法。可以通过Thread类的的构造方法 传递一个无参数,并且不返回值(返回void)的委托(ThreadStart),这个委托的 定义如下:
[ComVisibleAttribute(true)]
public delegate void ThreadStart()
我们可以通过如下的方法来建立并运行一个 线程。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MyThread
{
class Program
{
public static void myStaticThreadMethod()
{
Console.WriteLine("myStaticThreadMethod");
}
static void Main(string[] args)
{
Thread thread1 = new Thread(myStaticThreadMethod);
thread1.Start();// 只要使用Start方法,线程才会运行
}
}
}
除了运行静态的方法,还可以在线程中运行实例 方法,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MyThread
{
class Program
{
public void myThreadMethod()
{
Console.WriteLine("myThreadMethod");
}
static void Main(string[] args)
{
Thread thread2 = new Thread(new Program().myThreadMethod);
thread2.Start();
}
}
}