当前位置: 移动技术网 > IT编程>开发语言>c# > C#线程定义和使用方法详解

C#线程定义和使用方法详解

2019年07月18日  | 移动技术网IT编程  | 我要评论

一、c# 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(); 


}

如果读者的方法很简单,或出去某种目的,也可以通过匿名委托或lambda表达式来为thread的构造方法赋值,代码如下:

复制代码 代码如下:

thread thread3 = new thread(delegate() { console.writeline("匿名委托"); }); 
thread3.start(); 
thread thread4 = new thread(( ) => { console.writeline("lambda表达式"); }); 
thread4.start(); 

其中lambda表达式前面的( )表示没有参数。

为了区分不同的线程,还可以为thread类的name属性赋值,代码如下:

复制代码 代码如下:

thread thread5 = new thread(()=>{ console.writeline(thread.currentthread.name); }); 
thread5.name = "我的lamdba"; 
thread5.start();

如果将上面thread1至thread5放到一起执行,由于系统对线程的调度不同,输出的结果是不定的,如图1是一种可能的输出结果。

二、 定义一个线程类

我们可以将thread类封装在一个mythread类中,以使任何从mythread继承的类都具有多线程能力。mythread类的代码如下:

复制代码 代码如下:

using system; 
using system.collections.generic; 
using system.linq; 
using system.text; 
using system.threading; 
namespace mythread 

   abstract class mythread 

   thread thread = null; 

   abstract public void run(); 

public void start() 

if (thread == null) 
thread = new thread(run); 
thread.start(); 


}

可以用下面的代码来使用mythread类。

复制代码 代码如下:

class newthread : mythread 

  override public void run() 
  { 
  console.writeline("使用mythread建立并运行线程"); 
  } 
  } 

  static void main(string[] args) 
  { 

  newthread nt = new newthread(); 
  nt.start(); 
  }

我们还可以利用mythread来为线程传递任意复杂的参数。详细内容见下节。

三、c# thread类:为线程传递参数

thread类有一个带参数的委托类型的重载形式。这个委托的定义如下:

[comvisibleattribute(false)]

public delegate void parameterizedthreadstart(object obj)

 

这个thread类的构造方法的定义如下:

public thread(parameterizedthreadstart start);
下面的代码使用了这个带参数的委托向线程传递一个字符串参数:

复制代码 代码如下:

public static void mystaticparamthreadmethod(object obj) 

console.writeline(obj); 


static void main(string[] args) 

  thread thread = new thread(mystaticparamthreadmethod); 
  thread.start("通过委托的参数传值"); 
}

要注意的是,如果使用的是不带参数的委托,不能使用带参数的start方法运行线程,否则系统会抛出异常。但使用带参数的委托,可以使用thread.start()来运行线程,这时所传递的参数值为null。

也可以定义一个类来传递参数值,如下面的代码如下:

复制代码 代码如下:

class mydata 

private string d1; 
private int d2; 
public mydata(string d1, int d2) 

  this.d1 = d1; 
  this.d2 = d2; 

public void threadmethod() 

  console.writeline(d1); 
  console.writeline(d2); 



mydata mydata = new mydata("abcd",1234); 
thread thread = new thread(mydata.threadmethod); 
thread.start();

如果使用在第二节定义的mythread类,传递参数会显示更简单,代码如下:

复制代码 代码如下:

class newthread : mythread 

private string p1; 
private int p2; 
public newthread(string p1, int p2) 

this.p1 = p1; 
this.p2 = p2; 


override public void run() 

console.writeline(p1); 
console.writeline(p2); 



newthread newthread = new newthread("hello world", 4321); 
newthread.start();

四、前台和后台线程

使用thread建立的线程默认情况下是前台线程,在进程中,只要有一个前台线程未退出,进程就不会终止。主线程就是一个前台线程。而后台线程不管线程是否结束,只要所有的前台线程都退出(包括正常退出和异常退出)后,进程就会自动终止。一般后台线程用于处理时间较短的任务,如在一个web服务器中可以利用后台线程来处理客户端发过来的请求信息。而前台线程一般用于处理需要长时间等待的任务,如在web服务器中的监听客户端请求的程序,或是定时对某些系统资源进行扫描的程序。下面的代码演示了前台和后台线程的区别


复制代码 代码如下:

public static void mystaticthreadmethod() 

thread.sleep(3000); 


thread thread = new thread(mystaticthreadmethod); 
// thread.isbackground = true; 
thread.start();

如果运行上面的代码,程序会等待3秒后退出,如果将注释去掉,将thread设成后台线程,则程序会立即退出。

要注意的是,必须在调用start方法之前设置线程的类型,否则一但线程运行,将无法改变其类型。

通过beginxxx方法运行的线程都是后台线程。

五、c# thread类:判断多个线程是否都结束的两种方法

确定所有线程是否都完成了工作的方法有很多,如可以采用类似于对象计数器的方法,所谓对象计数器,就是一个对象被引用一次,这个计数器就加1,销毁引用就减1,如果引用数为0,则垃圾搜集器就会对这些引用数为0的对象进行回收。

方法一:线程计数器

线程也可以采用计数器的方法,即为所有需要监视的线程设一个线程计数器,每开始一个线程,在线程的执行方法中为这个计数器加1,如果某个线程结束(在线程执行方法的最后为这个计数器减1),为这个计数器减1。然后再开始一个线程,按着一定的时间间隔来监视这个计数器,如是棕个计数器为0,说明所有的线程都结束了。当然,也可以不用这个监视线程,而在每一个工作线程的最后(在为计数器减1的代码的后面)来监视这个计数器,也就是说,每一个工作线程在退出之前,还要负责检测这个计数器。使用这种方法不要忘了同步这个计数器变量啊,否则会产生意想不到的后果。

方法二:使用thread.join方法

join方法只有在线程结束时才继续执行下面的语句。可以对每一个线程调用它的join方法,但要注意,这个调用要在另一个线程里,而不要在主线程,否则程序会被阻塞的。

个人感觉这种方法比较好。

线程计数器方法演示:

复制代码 代码如下:

class threadcounter : mythread 

private static int count = 0; 
private int ms; 
private static void increment() 

lock (typeof(threadcounter))  // 必须同步计数器 

count++; 


private static void decrease() 

lock (typeof(threadcounter)) 

count--; 


private static int getcount() 

lock (typeof(threadcounter)) 

return count; 


public threadcounter(int ms) 

this.ms = ms; 

override public void run() 

increment(); 
thread.sleep(ms); 
console.writeline(ms.tostring()+"毫秒任务结束"); 
decrease(); 
if (getcount() == 0) 
console.writeline("所有任务结束"); 



 
threadcounter counter1 = new threadcounter(3000); 
threadcounter counter2 = new threadcounter(5000); 
threadcounter counter3 = new threadcounter(7000); 

counter1.start(); 
counter2.start(); 
counter3.start();

上面的代码虽然在大多数的时候可以正常工作,但却存在一个隐患,就是如果某个线程,假设是counter1,在运行后,由于某些原因,其他的线程并未运行,在这种情况下,在counter1运行完后,仍然可以显示出“所有任务结束”的提示信息,但是counter2和counter3还并未运行。为了消除这个隐患,可以将increment方法从run中移除,将其放到threadcounter的构造方法中,在这时,increment方法中的lock也可以去掉了。代码如:

复制代码 代码如下:

public threadcounter(int ms) 
 { 
 this.ms = ms; 
 increment(); 
 }

运行上面的程序后,将显示如图2的结果。

使用thread.join方法演示

复制代码 代码如下:

private static void threadmethod(object obj) 

thread.sleep(int32.parse(obj.tostring())); 
console.writeline(obj + "毫秒任务结束"); 

private static void joinallthread(object obj) 

thread[] threads = obj as thread[]; 
foreach (thread t in threads) 
t.join(); 
console.writeline("所有的线程结束"); 


static void main(string[] args) 

thread thread1 = new thread(threadmethod); 
thread thread2 = new thread(threadmethod); 
thread thread3 = new thread(threadmethod); 

 thread1.start(3000); 
 thread2.start(5000); 
 thread3.start(7000); 

 thread jointhread = new thread(joinallthread); 
 jointhread.start(new thread[] { thread1, thread2, thread3 }); 

}

在运行上面的代码后,将会得到和图2同样的运行结果。上述两种方法都没有线程数的限制,当然,仍然会受到操作系统和硬件资源的限制。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网