淺析c# 線程同步
同步是一種只允許一個線程在特定時間訪問某些資源的技術(shù)。沒有其他線程可以中斷,直到所分配的線程或當(dāng)前訪問線程訪問數(shù)據(jù)完成其任務(wù)。
在多線程程序中,允許線程訪問任何資源所需的執(zhí)行時間。線程共享資源并異步執(zhí)行。 訪問共享資源(數(shù)據(jù))是有時可能會暫停系統(tǒng)的關(guān)鍵任務(wù)。所以可以通過線程同步來處理它。
主要場景如:存款,取款等交易業(yè)務(wù)處理。
線程同步的優(yōu)點(diǎn)
- 一致性維護(hù)
- 無線程干擾
C#鎖定
使用 C# lock
關(guān)鍵字同步執(zhí)行程序。它用于為當(dāng)前線程鎖定,執(zhí)行任務(wù),然后釋放鎖定。它確保其他線程在執(zhí)行完成之前不會中斷執(zhí)行。
下面,創(chuàng)建兩個非同步和同步的例子。
C# 示例:非同步
在這個例子中,我們不使用鎖。此示例異步執(zhí)行。換句話說,線程之間存在上下文切換。
using System; using System.Threading; class Printer { public void PrintTable() { for (int i = 1; i <= 5; i++) { Thread t = Thread.CurrentThread; Thread.Sleep(200); Console.WriteLine(t.Name+" "+i); } } } class Program { public static void Main(string[] args) { Printer p = new Printer(); Thread t1 = new Thread(new ThreadStart(p.PrintTable)); Thread t2 = new Thread(new ThreadStart(p.PrintTable)); t1.Name = "Thread 1 :"; t2.Name = "Thread 2 :"; t1.Start(); t2.Start(); } }
執(zhí)行上面示例代碼,可以看到以下輸出結(jié)果 -
Thread 2 : 1
Thread 1 : 1
Thread 2 : 2
Thread 1 : 2
Thread 2 : 3
Thread 1 : 3
Thread 2 : 4
Thread 1 : 4
Thread 2 : 5
Thread 1 : 5
C# 線程同步示例
在這個例子中,我們使用lock
塊,因此示例同步執(zhí)行。 換句話說,線程之間沒有上下文切換。在輸出部分,可以看到第二個線程在第一個線程完成任務(wù)之后開始執(zhí)行。
using System; using System.Threading; class Printer { public void PrintTable() { lock (this) { for (int i = 1; i <= 5; i++) { Thread t = Thread.CurrentThread; Thread.Sleep(100); Console.WriteLine(t.Name + " " + i); } } } } class Program { public static void Main(string[] args) { Printer p = new Printer(); Thread t1 = new Thread(new ThreadStart(p.PrintTable)); Thread t2 = new Thread(new ThreadStart(p.PrintTable)); t1.Name = "Thread 1 :"; t2.Name = "Thread 2 :"; t1.Start(); t2.Start(); } }
執(zhí)行上面示例代碼,可以看到以下輸出結(jié)果 -
Thread 1 : 1
Thread 1 : 2
Thread 1 : 3
Thread 1 : 4
Thread 1 : 5
Thread 2 : 1
Thread 2 : 2
Thread 2 : 3
Thread 2 : 4
Thread 2 : 5
以上就是淺析c# 線程同步的詳細(xì)內(nèi)容,更多關(guān)于c# 線程同步的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#實(shí)現(xiàn)計(jì)算一個點(diǎn)圍繞另一個點(diǎn)旋轉(zhuǎn)指定弧度后坐標(biāo)值的方法
這篇文章主要介紹了C#實(shí)現(xiàn)計(jì)算一個點(diǎn)圍繞另一個點(diǎn)旋轉(zhuǎn)指定弧度后坐標(biāo)值的方法,涉及C#針對坐標(biāo)的數(shù)學(xué)運(yùn)算相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08Unity登錄注冊時限制發(fā)送驗(yàn)證碼次數(shù)功能的解決方法
這篇文章主要為大家詳細(xì)介紹了Unity登錄注冊時限制發(fā)送驗(yàn)證碼次數(shù)功能的解決方案,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-01-01C#實(shí)現(xiàn)判斷操作系統(tǒng)是否為Win8以上版本
這篇文章主要介紹了C#實(shí)現(xiàn)判斷操作系統(tǒng)是否為Win8以上版本,本文講解了利用C#獲取OS的版本號、利用反射獲取當(dāng)前正在運(yùn)行的程序的版本信息、 利用C#判斷當(dāng)前操作系統(tǒng)是否為Win8系統(tǒng)等內(nèi)容,需要的朋友可以參考下2015-06-06