使用C#的System.Threading命名空间可以方便的编写多线程应用程序
首先声明一个线程,然后把要用该线程运行的程序名作为参数传给线程构造函数
//定义一个方法
public void DoWork()
{
//do some work
}
//把此方法传递给线程构造函数
System.Threading.Thread myThread = new System.Threading.Thread(DoWork);
//启动线程
myThread.Start();
下面写一个具体的例子
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ThreadExample
{
class Worker
{
private volatile bool _shouldStop=false;
public void DoWork()
{
while (!_shouldStop)
{
Console.WriteLine("Worker Threading: working......");
}
Console.WriteLine("Worker Threading: end");
}
public void StopWork()
{
_shouldStop = true;
}
}
class Program
{
static void Main(string[] args)
{
Worker worker = new Worker();
System.Threading.Thread workerThread = new System.Threading.Thread(worker.DoWork);
workerThread.Start();//workerThread线程是否已经开始执行
while(!workerThread.IsAlive);//
Thread.Sleep(200);//阻塞当前进程一段时间
worker.StopWork();
workerThread.Join();//阻塞当前进程 直到workerThread结束返回
Console.WriteLine("main thread: Worker thread has terminated.");
Console.ReadLine();
}
}
}