C#線程定義和使用方法詳解
一、C# Thread類的基本用法
通過System.Threading.Thread類可以開始新的線程,并在線程堆棧中運(yùn)行靜態(tài)或?qū)嵗椒?。可以通過Thread類的的構(gòu)造方法傳遞一個(gè)無參數(shù),并且不返回值(返回void)的委托(ThreadStart),這個(gè)委托的定義如下:
[ComVisibleAttribute(true)]
public delegate void ThreadStart()
我們可以通過如下的方法來建立并運(yùn)行一個(gè)線程。
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方法,線程才會(huì)運(yùn)行
}
}
}
除了運(yùn)行靜態(tài)的方法,還可以在線程中運(yùn)行實(shí)例方法,代碼如下:
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();
}
}
}
如果讀者的方法很簡(jiǎn)單,或出去某種目的,也可以通過匿名委托或Lambda表達(dá)式來為Thread的構(gòu)造方法賦值,代碼如下:
Thread thread3 = new Thread(delegate() { Console.WriteLine("匿名委托"); });
thread3.Start();
Thread thread4 = new Thread(( ) => { Console.WriteLine("Lambda表達(dá)式"); });
thread4.Start();
其中Lambda表達(dá)式前面的( )表示沒有參數(shù)。
為了區(qū)分不同的線程,還可以為Thread類的Name屬性賦值,代碼如下:
Thread thread5 = new Thread(()=>{ Console.WriteLine(Thread.CurrentThread.Name); });
thread5.Name = "我的Lamdba";
thread5.Start();
如果將上面thread1至thread5放到一起執(zhí)行,由于系統(tǒng)對(duì)線程的調(diào)度不同,輸出的結(jié)果是不定的,如圖1是一種可能的輸出結(jié)果。
二、 定義一個(gè)線程類
我們可以將Thread類封裝在一個(gè)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建立并運(yùn)行線程");
}
}
static void Main(string[] args)
{
NewThread nt = new NewThread();
nt.start();
}
我們還可以利用MyThread來為線程傳遞任意復(fù)雜的參數(shù)。詳細(xì)內(nèi)容見下節(jié)。
三、C# Thread類:為線程傳遞參數(shù)
Thread類有一個(gè)帶參數(shù)的委托類型的重載形式。這個(gè)委托的定義如下:
[ComVisibleAttribute(false)]
public delegate void ParameterizedThreadStart(Object obj)
這個(gè)Thread類的構(gòu)造方法的定義如下:
public Thread(ParameterizedThreadStart start);
下面的代碼使用了這個(gè)帶參數(shù)的委托向線程傳遞一個(gè)字符串參數(shù):
public static void myStaticParamThreadMethod(Object obj)
{
Console.WriteLine(obj);
}
static void Main(string[] args)
{
Thread thread = new Thread(myStaticParamThreadMethod);
thread.Start("通過委托的參數(shù)傳值");
}
要注意的是,如果使用的是不帶參數(shù)的委托,不能使用帶參數(shù)的Start方法運(yùn)行線程,否則系統(tǒng)會(huì)拋出異常。但使用帶參數(shù)的委托,可以使用thread.Start()來運(yùn)行線程,這時(shí)所傳遞的參數(shù)值為null。
也可以定義一個(gè)類來傳遞參數(shù)值,如下面的代碼如下:
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();
如果使用在第二節(jié)定義的MyThread類,傳遞參數(shù)會(huì)顯示更簡(jiǎn)單,代碼如下:
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();
四、前臺(tái)和后臺(tái)線程
使用Thread建立的線程默認(rèn)情況下是前臺(tái)線程,在進(jìn)程中,只要有一個(gè)前臺(tái)線程未退出,進(jìn)程就不會(huì)終止。主線程就是一個(gè)前臺(tái)線程。而后臺(tái)線程不管線程是否結(jié)束,只要所有的前臺(tái)線程都退出(包括正常退出和異常退出)后,進(jìn)程就會(huì)自動(dòng)終止。一般后臺(tái)線程用于處理時(shí)間較短的任務(wù),如在一個(gè)Web服務(wù)器中可以利用后臺(tái)線程來處理客戶端發(fā)過來的請(qǐng)求信息。而前臺(tái)線程一般用于處理需要長時(shí)間等待的任務(wù),如在Web服務(wù)器中的監(jiān)聽客戶端請(qǐng)求的程序,或是定時(shí)對(duì)某些系統(tǒng)資源進(jìn)行掃描的程序。下面的代碼演示了前臺(tái)和后臺(tái)線程的區(qū)別
public static void myStaticThreadMethod()
{
Thread.Sleep(3000);
}
Thread thread = new Thread(myStaticThreadMethod);
// thread.IsBackground = true;
thread.Start();
如果運(yùn)行上面的代碼,程序會(huì)等待3秒后退出,如果將注釋去掉,將thread設(shè)成后臺(tái)線程,則程序會(huì)立即退出。
要注意的是,必須在調(diào)用Start方法之前設(shè)置線程的類型,否則一但線程運(yùn)行,將無法改變其類型。
通過BeginXXX方法運(yùn)行的線程都是后臺(tái)線程。
五、C# Thread類:判斷多個(gè)線程是否都結(jié)束的兩種方法
確定所有線程是否都完成了工作的方法有很多,如可以采用類似于對(duì)象計(jì)數(shù)器的方法,所謂對(duì)象計(jì)數(shù)器,就是一個(gè)對(duì)象被引用一次,這個(gè)計(jì)數(shù)器就加1,銷毀引用就減1,如果引用數(shù)為0,則垃圾搜集器就會(huì)對(duì)這些引用數(shù)為0的對(duì)象進(jìn)行回收。
方法一:線程計(jì)數(shù)器
線程也可以采用計(jì)數(shù)器的方法,即為所有需要監(jiān)視的線程設(shè)一個(gè)線程計(jì)數(shù)器,每開始一個(gè)線程,在線程的執(zhí)行方法中為這個(gè)計(jì)數(shù)器加1,如果某個(gè)線程結(jié)束(在線程執(zhí)行方法的最后為這個(gè)計(jì)數(shù)器減1),為這個(gè)計(jì)數(shù)器減1。然后再開始一個(gè)線程,按著一定的時(shí)間間隔來監(jiān)視這個(gè)計(jì)數(shù)器,如是棕個(gè)計(jì)數(shù)器為0,說明所有的線程都結(jié)束了。當(dāng)然,也可以不用這個(gè)監(jiān)視線程,而在每一個(gè)工作線程的最后(在為計(jì)數(shù)器減1的代碼的后面)來監(jiān)視這個(gè)計(jì)數(shù)器,也就是說,每一個(gè)工作線程在退出之前,還要負(fù)責(zé)檢測(cè)這個(gè)計(jì)數(shù)器。使用這種方法不要忘了同步這個(gè)計(jì)數(shù)器變量啊,否則會(huì)產(chǎn)生意想不到的后果。
方法二:使用Thread.join方法
join方法只有在線程結(jié)束時(shí)才繼續(xù)執(zhí)行下面的語句??梢詫?duì)每一個(gè)線程調(diào)用它的join方法,但要注意,這個(gè)調(diào)用要在另一個(gè)線程里,而不要在主線程,否則程序會(huì)被阻塞的。
個(gè)人感覺這種方法比較好。
線程計(jì)數(shù)器方法演示:
class ThreadCounter : MyThread
{
private static int count = 0;
private int ms;
private static void increment()
{
lock (typeof(ThreadCounter)) // 必須同步計(jì)數(shù)器
{
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()+"毫秒任務(wù)結(jié)束");
decrease();
if (getCount() == 0)
Console.WriteLine("所有任務(wù)結(jié)束");
}
}
ThreadCounter counter1 = new ThreadCounter(3000);
ThreadCounter counter2 = new ThreadCounter(5000);
ThreadCounter counter3 = new ThreadCounter(7000);
counter1.start();
counter2.start();
counter3.start();
上面的代碼雖然在大多數(shù)的時(shí)候可以正常工作,但卻存在一個(gè)隱患,就是如果某個(gè)線程,假設(shè)是counter1,在運(yùn)行后,由于某些原因,其他的線程并未運(yùn)行,在這種情況下,在counter1運(yùn)行完后,仍然可以顯示出“所有任務(wù)結(jié)束”的提示信息,但是counter2和counter3還并未運(yùn)行。為了消除這個(gè)隱患,可以將increment方法從run中移除,將其放到ThreadCounter的構(gòu)造方法中,在這時(shí),increment方法中的lock也可以去掉了。代碼如:
public ThreadCounter(int ms)
{
this.ms = ms;
increment();
}
運(yùn)行上面的程序后,將顯示如圖2的結(jié)果。
使用Thread.join方法演示
private static void threadMethod(Object obj)
{
Thread.Sleep(Int32.Parse(obj.ToString()));
Console.WriteLine(obj + "毫秒任務(wù)結(jié)束");
}
private static void joinAllThread(object obj)
{
Thread[] threads = obj as Thread[];
foreach (Thread t in threads)
t.Join();
Console.WriteLine("所有的線程結(jié)束");
}
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 });
}
在運(yùn)行上面的代碼后,將會(huì)得到和圖2同樣的運(yùn)行結(jié)果。上述兩種方法都沒有線程數(shù)的限制,當(dāng)然,仍然會(huì)受到操作系統(tǒng)和硬件資源的限制。
- c#使用ManagedWifi查看當(dāng)前Wifi信號(hào)并選擇wifi的示例
- C#獲取進(jìn)程的主窗口句柄的實(shí)現(xiàn)方法
- C#獲取進(jìn)程和對(duì)進(jìn)程的操作
- C#獲取Windows進(jìn)程監(jiān)聽的TCP/UDP端口實(shí)例
- C#控制IE進(jìn)程關(guān)閉和緩存清理的實(shí)現(xiàn)代碼
- C#網(wǎng)絡(luò)編程基礎(chǔ)之進(jìn)程和線程詳解
- C#多線程傳遞參數(shù)及任務(wù)用法示例
- C#子線程更新UI控件的方法實(shí)例總結(jié)
- 淺解關(guān)于C#多線程的介紹
- c#多線程中Lock()關(guān)鍵字的用法小結(jié)
- C#信號(hào)量用法簡(jiǎn)單示例
相關(guān)文章
淺談c#表達(dá)式樹Expression簡(jiǎn)單類型比較demo
下面小編就為大家?guī)硪黄獪\談c#表達(dá)式樹Expression簡(jiǎn)單類型比較demo。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02使用c#實(shí)現(xiàn)微信自動(dòng)化功能
這篇文章主要介紹了使用c#實(shí)現(xiàn)微信自動(dòng)化,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-08-08C# DataSet查看返回結(jié)果集的實(shí)現(xiàn)
這篇文章主要介紹了C# DataSet查看返回結(jié)果集的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10c#訪問this關(guān)鍵字和base關(guān)鍵字示例
this關(guān)鍵字引用類的當(dāng)前實(shí)例。靜態(tài)成員方法中不能使用this關(guān)鍵字,this關(guān)鍵字只能在實(shí)例構(gòu)造函數(shù)、實(shí)例方法或?qū)嵗L問器中使用。base關(guān)鍵字用于從派生類中訪問基類的成員。下面學(xué)習(xí)一下這二個(gè)關(guān)鍵字的使用方法2014-01-01C#實(shí)現(xiàn)NPOI的Excel導(dǎo)出詳解
這篇文章主要介紹了C#實(shí)現(xiàn)NPOI的Excel導(dǎo)出的示例代碼,文中的實(shí)現(xiàn)過程講解詳細(xì),對(duì)我們的學(xué)習(xí)或工作有一定的幫助,感興趣的可以跟隨小編一起學(xué)習(xí)一下2022-01-01