c# Lock Thread

  1. Lock : 關鍵字將語句塊標記爲臨界區,方法是獲取給定對象的互斥鎖,執行語句,然後釋放該鎖。此語句的形式如下:
    Object thisLock = new Object();
    lock (thisLock)
    {
    // Critical code section
    }
    給定的對象設置鎖

  2. Lock : 確保當一個線程位於代碼的臨界區時,另一個線程不進入臨界區。如果其他線程試圖進入鎖定的代碼,則它將一直等待(即被阻止),直到該對象被釋放。
    lock 調用塊開始位置的 Enter 和塊結束位置的 Exit。
    通常,應避免鎖定 public 類型,否則實例將超出代碼的控制範圍。常見的結構 lock (this)、lock (typeof (MyType)) 和 lock (“myLock”) 違反此準則:
    ● 如果實例可以被公共訪問,將出現 lock (this) 問題。
    ● 如果 MyType 可以被公共訪問,將出現 lock (typeof (MyType)) 問題。
    ● 由於進程中使用同一字符串的任何其他代碼將共享同一個鎖,所以出現 lock(“myLock”) 問題。
    最佳做法是定義 private 對象來鎖定, 或 private static 對象變量來保護所有實例所共有的數據。

創建一個簡單線程
using System;
using System.Threading;

class ThreadTest
{
public void RunMe()
{
Console.WriteLine(“RunMe called”);
}

static void Main()
{
    ThreadTest b = new ThreadTest();
    Thread t = new Thread(b.RunMe);
    t.Start();
}

}

下面是一個 例子,如果是 想要把 Lock 去掉, 那就得保證 下面只執行一次,否則他們是同步的,隨時都會訪問上一次的對象。

   for (int i = 0; i < 10; i++)
        {
            threads[i].Start();
        }

具體代碼如下

using System;
using System.Threading;

class Account
{
    private Object thisLock = new Object();
    int balance;

    Random r = new Random();

    public Account(int initial)
    {
        balance = initial;
    }

    int Withdraw(int amount)
    {

        // This condition will never be true unless the lock statement
        // is commented out:
        if (balance < 0)
        {
            throw new Exception("Negative Balance");
        }

        // Comment out the next line to see the effect of leaving out 
        // the lock keyword:
        lock(thisLock)
        {
            if (balance >= amount)
            {
                Console.WriteLine("Balance before Withdrawal :  " + balance);
                Console.WriteLine("Amount to Withdraw        : -" + amount);
                balance = balance - amount;
                Console.WriteLine("Balance after Withdrawal  :  " + balance);
                return amount;
            }
            else
            {
                return 0; // transaction rejected
            }
        }
    }

    public void DoTransactions()
    {
        for (int i = 0; i < 100; i++)
        {
            Withdraw(r.Next(1, 100));
        }
    }
}

class Test
{
    static void Main()
    {
        Thread[] threads = new Thread[10];
        Account acc = new Account(1000);
        for (int i = 0; i < 10; i++)
        {
            Thread t = new Thread(new ThreadStart(acc.DoTransactions));
            threads[i] = t;
        }
        for (int i = 0; i < 10; i++)
        {
            threads[i].Start();
        }
    }
}

線程 : 分爲 前臺,後臺,
前臺 : Main退出的時候,就依然運行。
後臺 : Main退出的時候,也結束。

    static void Main(string[] args)
    {
        Thread obj1 = new Thread(Function1);
        obj1.IsBackground = true;
        obj1.Start();


        Console.WriteLine("There is a Constrol");
    }

    static void Function1()
    {
        Console.WriteLine("The Enter");
        Console.ReadLine();
    Console.WriteLine("The Exit");
    }

    static void Function2()
    {
        Console.WriteLine("Function The Enter");

    }
發佈了76 篇原創文章 · 獲贊 23 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章