Thread類線程常用操作

創(chuàng)建線程
線程是通過擴(kuò)展 Thread 類創(chuàng)建的。擴(kuò)展的 Thread 類調(diào)用 Start() 方法來開始子線程的執(zhí)行。
下面的程序演示了這個(gè)概念:
class ThreadCreationProgram{public static void CallToChildThread(){Console.WriteLine("Child thread starts");}static void Main(string[] args){ThreadStart childref = new ThreadStart(CallToChildThread);Console.WriteLine("In Main: Creating the Child thread");Thread childThread = new Thread(childref);childThread.Start();Console.ReadKey();}}
當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:
In Main: Creating the Child threadChild thread starts
管理線程
Thread 類提供了各種管理線程的方法。
下面的實(shí)例演示了 sleep() 方法的使用,用于在一個(gè)特定的時(shí)間暫停線程。
class ThreadCreationProgram{public static void CallToChildThread(){Console.WriteLine("Child thread starts");// 線程暫停 5000 毫秒int sleepfor = 5000;Console.WriteLine("Child Thread Paused for {0} seconds",sleepfor / 1000);Thread.Sleep(sleepfor);Console.WriteLine("Child thread resumes");}static void Main(string[] args){ThreadStart childref = new ThreadStart(CallToChildThread);Console.WriteLine("In Main: Creating the Child thread");Thread childThread = new Thread(childref);childThread.Start();Console.ReadKey();}}
當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:
In Main: Creating the Child threadChild thread startsChild Thread Paused for 5 secondsChild thread resumes
銷毀線程
Abort() 方法用于銷毀線程。
通過拋出 threadabortexception 在運(yùn)行時(shí)中止線程。這個(gè)異常不能被捕獲,如果有 finally 塊,控制會(huì)被送至 finally 塊。
下面的程序說明了這點(diǎn):
class ThreadCreationProgram{public static void CallToChildThread(){try{Console.WriteLine("Child thread starts");// 計(jì)數(shù)到 10for (int counter = 0; counter <= 10; counter++){Thread.Sleep(500);Console.WriteLine(counter);}Console.WriteLine("Child Thread Completed");}catch (ThreadAbortException e){Console.WriteLine("Thread Abort Exception");}finally{Console.WriteLine("Couldn't catch the Thread Exception");}}static void Main(string[] args){ThreadStart childref = new ThreadStart(CallToChildThread);Console.WriteLine("In Main: Creating the Child thread");Thread childThread = new Thread(childref);childThread.Start();// 停止主線程一段時(shí)間Thread.Sleep(2000);// 現(xiàn)在中止子線程Console.WriteLine("In Main: Aborting the Child thread");childThread.Abort();Console.ReadKey();}}
當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:
In Main: Creating the Child threadChild thread starts012In Main: Aborting the Child threadThread Abort Exceptioncatch the Thread Exception
【推薦】.NET Core開發(fā)實(shí)戰(zhàn)視頻課程 ★★★
.NET Core實(shí)戰(zhàn)項(xiàng)目之CMS 第一章 入門篇-開篇及總體規(guī)劃
【.NET Core微服務(wù)實(shí)戰(zhàn)-統(tǒng)一身份認(rèn)證】開篇及目錄索引
Redis基本使用及百億數(shù)據(jù)量中的使用技巧分享(附視頻地址及觀看指南)
.NET Core中的一個(gè)接口多種實(shí)現(xiàn)的依賴注入與動(dòng)態(tài)選擇看這篇就夠了
10個(gè)小技巧助您寫出高性能的ASP.NET Core代碼
用abp vNext快速開發(fā)Quartz.NET定時(shí)任務(wù)管理界面
在ASP.NET Core中創(chuàng)建基于Quartz.NET托管服務(wù)輕松實(shí)現(xiàn)作業(yè)調(diào)度
現(xiàn)身說法:實(shí)際業(yè)務(wù)出發(fā)分析百億數(shù)據(jù)量下的多表查詢優(yōu)化
