跳轉至內容

C# 程式設計/關鍵字/lock

來自華夏公益教科書,自由的教科書

在多執行緒應用程式中,lock 關鍵字允許一段程式碼獨佔使用資源。如果當一段程式碼嘗試鎖定某個物件時,該物件的鎖已被其他程式碼佔用,則這段程式碼所在的執行緒將被阻塞,直到該物件可用。

using System;
using System.Threading;

class LockDemo
{
    private static int number = 0;
    private static object lockObject = new object();
    
    private static void DoSomething()
    {
        while (true)
        {
            lock (lockObject)
            {
                int originalNumber = number;
                
                number += 1;
                Thread.Sleep((new Random()).Next(1000)); // sleep for a random amount of time
                number += 1;
                Thread.Sleep((new Random()).Next(1000)); // sleep again
                
                Console.Write("Expecting number to be " + (originalNumber + 2).ToString());
                Console.WriteLine(", and it is: " + number.ToString());
                // without the lock statement, the above would produce unexpected results, 
                // since the other thread may have added 2 to the number while we were sleeping.
            }
        }
    }
    
    public static void Main()
    {
        Thread t = new Thread(new ThreadStart(DoSomething));
        
        t.Start();
        DoSomething(); // at this point, two instances of DoSomething are running at the same time.
    }
}

lock 語句的引數必須是物件引用,而不是值型別。

class LockDemo2
{
    private int number;
    private object obj = new object();
    
    public void DoSomething()
    {
        lock (this) // ok
        {
            ...
        }
        
        lock (number) // not ok, number is not a reference
        {
            ...
        }
        
        lock (obj) // ok, obj is a reference
        {
            ...
        }
    }
}



C# 關鍵字
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using var virtual
void volatile while
特殊的 C# 識別符號(上下文關鍵字)
add alias async await dynamic
get global nameof partial remove
set value when where yield
上下文關鍵字(用於查詢)
ascending by descending equals from
group in into join let
on orderby select where
華夏公益教科書