您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

C#的多线程机制初探(2)

2024/4/15 4:58:45发布11次查看
下面我们就动手来创建一个线程,使用thread类创建线程时,只需提供线程入口即可。线程入口使程序知道该让这个线程干什么事,在c#中,线程入口是通过threadstart代理(delegate)来提供的,你可以把threadstart理解为一个函数指针,指向线程要执行的函数,当调用thread.start()方法后,线程就开始执行threadstart所代表或者说指向的函数。
打开你的vs.net,新建一个控制台应用程序(console application),下面这些代码将让你体味到完全控制一个线程的无穷乐趣!
//threadtest.cs
using system; 
using system.threading;
namespace threadtest 
{ 
public class alpha 

public void beta() 

while (true) 

console.writeline(alpha.beta is running in its own thread.); 


};
public class simple 

public static int main() 

console.writeline(thread start/stop/join sample);
alpha oalpha = new alpha(); 
//这里创建一个线程,使之执行alpha类的beta()方法 
thread othread = new thread(new threadstart(oalpha.beta)); 
othread.start(); 
while (!othread.isalive); 
thread.sleep(1); 
othread.abort(); 
othread.join(); 
console.writeline(); 
console.writeline(alpha.beta has finished); 
try 

console.writeline(try to restart the alpha.beta thread); 
othread.start(); 

catch (threadstateexception) 

console.write(threadstateexception trying to restart alpha.beta. ); 
console.writeline(expected since aborted threads cannot be restarted.); 
console.readline(); 

return 0; 


}
这段程序包含两个类alpha和simple,在创建线程othread时我们用指向alpha.beta()方法的初始化了threadstart代理(delegate)对象,当我们创建的线程othread调用othread.start()方法启动时,实际上程序运行的是alpha.beta()方法:
alpha oalpha = new alpha(); 
thread othread = new thread(new threadstart(oalpha.beta)); 
othread.start();
然后在main()函数的while循环中,我们使用静态方法thread.sleep()让主线程停了1ms,这段时间cpu转向执行线程othread。然后我们试图用thread.abort()方法终止线程othread,注意后面的othread.join(),thread.join()方法使主线程等待,直到othread线程结束。你可以给thread.join()方法指定一个int型的参数作为等待的最长时间。之后,我们试图用thread.start()方法重新启动线程othread,但是显然abort()方法带来的后果是不可恢复的终止线程,所以最后程序会抛出threadstateexception异常
 以上就是c#的多线程机制初探(2)的内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product