溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

c# 線程同步

發(fā)布時(shí)間:2020-09-24 09:20:02 來(lái)源:億速云 閱讀:130 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)c# 線程同步,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

同步是一種只允許一個(gè)線程在特定時(shí)間訪問(wèn)某些資源的技術(shù)。沒(méi)有其他線程可以中斷,直到所分配的線程或當(dāng)前訪問(wèn)線程訪問(wèn)數(shù)據(jù)完成其任務(wù)。

在多線程程序中,允許線程訪問(wèn)任何資源所需的執(zhí)行時(shí)間。線程共享資源并異步執(zhí)行。 訪問(wèn)共享資源(數(shù)據(jù))是有時(shí)可能會(huì)暫停系統(tǒng)的關(guān)鍵任務(wù)。所以可以通過(guò)線程同步來(lái)處理它。

主要場(chǎng)景如:存款,取款等交易業(yè)務(wù)處理。

線程同步的優(yōu)點(diǎn)

  • 一致性維護(hù)
  • 無(wú)線程干擾

C#鎖定

使用 C# lock關(guān)鍵字同步執(zhí)行程序。它用于為當(dāng)前線程鎖定,執(zhí)行任務(wù),然后釋放鎖定。它確保其他線程在執(zhí)行完成之前不會(huì)中斷執(zhí)行。

下面,創(chuàng)建兩個(gè)非同步和同步的例子。

C# 示例:非同步

在這個(gè)例子中,我們不使用鎖。此示例異步執(zhí)行。換句話說(shuō),線程之間存在上下文切換。

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# 線程同步示例

在這個(gè)例子中,我們使用lock塊,因此示例同步執(zhí)行。 換句話說(shuō),線程之間沒(méi)有上下文切換。在輸出部分,可以看到第二個(gè)線程在第一個(gè)線程完成任務(wù)之后開(kāi)始執(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# 線程同步了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI