本文深入探討 C# 進階特性:自訂屬性與反射實現中繼資料驅動、多執行緒建立與控制、同步化機制,並提供完整可執行範例。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)]
public class CodeReviewAttribute : Attribute
{
public string Date { get; }
public string Reviewer { get; }
public string Comment { get; set; }
public CodeReviewAttribute(string date, string reviewer)
{
Date = date; Reviewer = reviewer;
}
}
[CodeReview("2024-01-15", "Alice", Comment = "效能優化完成")]
public class Employee { ... }
MemberInfo info = typeof(Employee);
foreach (var attr in info.GetCustomAttributes(false))
{
if (attr is CodeReviewAttribute cra)
Console.WriteLine($"{cra.Date} by {cra.Reviewer}: {cra.Comment}");
}
Assembly asm = Assembly.Load("mscorlib.dll");
foreach (Type t in asm.GetTypes())
Console.WriteLine(t.FullName);
Math.Pow
Type mathType = Type.GetType("System.Math");
object obj = Activator.CreateInstance(mathType);
MethodInfo pow = mathType.GetMethod("Pow", new[] { typeof(double), typeof(double) });
object result = pow.Invoke(obj, new object[] { 5.0, 3.0 }); // 125
using System.Threading;
Thread t1 = new Thread(CountUp) { Name = "Thread-1" };
Thread t2 = new Thread(CountUp) { Name = "Thread-2" };
t1.Start(); t2.Start();
t1.Start(); t2.Start();
t1.Join(); t2.Join(); // 等待結束
Console.WriteLine("所有執行緒完成");
Thread.Sleep(1000); // 休眠 1 秒
t1.Abort(); // 強制中止(不推薦,改用 CancellationToken)
Interlocked 原子操作
int counter = 0;
Interlocked.Increment(ref counter); // 執行緒安全遞增
lock 關鍵字(Monitor 封裝)
object _lock = new object();
int shared = 0;
void SafeIncrement()
{
lock (_lock)
{
int temp = shared;
Thread.Sleep(1); // 模擬工作
shared = temp + 1;
Console.WriteLine($"{Thread.CurrentThread.Name}: {shared}");
}
}
注意:lock(this)或lock(typeof(Type))易造成死鎖,建議使用private readonly object _lock = new();專用鎖定物件。
Mutex:跨處理序同步Semaphore/SemaphoreSlim:控制並發存取數ReaderWriterLockSlim:讀多寫少場景優化Monitor.Wait/Pulse:條件變數模式新專案建議優先使用 Task、async/await、Parallel、PLINQ,而非手動管理 Thread:
await Task.Run(() => DoWork());
Parallel.For(0, 100, i => Process(i));
屬性與反射賦予 C# 強大的中繼資料驅動能力;多執行緒與同步化是高併發系統的基石。理解底層機制(Monitor、Interlocked)有助於排查死鎖與競爭條件,但在現代開發中,請優先擁抱 Task 與 async/await 的高階抽象。