多线程,顾名思义,就是在一个应用中实现多个任务,在c#中,线程Threads包含在System.Threading的namespace中。
一、创建一个threads,最简单的方法就是创建一个threads实例
eg:
Thread myThread = new Thread( new ThreadStart(·····) );
执行threads
myThread.Start();
使用threads的一个实例:
Thread myThread = new Thread( new ThreadStart(Incrementer) );
myThread.Start(); console.WritLine("执行到此”); public void Incrementer( ) { for (int i =0;i<1000;i++) { Console.WriteLine("Incrementer: {0}", i);Thread.sleep(1000);
} }
在一个程序中执行一个包含此实例的任务,当到达了threads.start();时,将执行Incrementer操作中的Consloe.WriteLine操作,当执行完之后,才会继续执行threads.start();后面的操作,在这个实例中,会向控制台输出“执行到此”。
注意到Incrementer中有 Thread.sleep(1000);语句,该语句是将此线程停止1秒,每一秒向控制台输出一个writeline语句。Thread.sleep()中时间默认为一毫秒为单位。
下面是threads类中非常重要的方法:
Start():启动线程;
Sleep(int):静态方法,暂停当前线程指定的毫秒数;
Abort():通常使用该方法来终止一个线程;
Suspend():该方法并不终止未完成的线程,它仅仅挂起线程,以后还可恢复;
Resume():恢复被Suspend()方法挂起的线程的执行。
使用threads的一个实例:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace thr{ class Program { static void Main(string[] args) { Console.WriteLine("start"); Thread th1 = new Thread(Thread1); th1.Start(); Console.WriteLine("middle"); Thread th2 = new Thread(Thread2); th2.Start(); Console.WriteLine("end"); Thread th3 = new Thread(Thread3); th3.Start(); } public static void Thread1() { for (int i = 0; i < 10; i++) Console.WriteLine("Thread1 exec: {0}", i); } public static void Thread2() { for (int j = 0; j < 10; j++) Console.WriteLine("Thread2 exec: {0}", j); } public static void Thread3() { for (int a = 0; a < 10; a++) Console.WriteLine("Thread3 exec: {0}", a); } }}
结果为: