多线程同步技术全解析
1. 使用 lock 关键字
在多线程编程中,经常需要使用Monitor进行同步,但try/finally块容易被遗忘。为此,C# 提供了lock关键字来处理这种锁定同步模式。以下是使用lock关键字的示例代码:
using System; using System.Threading; using System.Threading.Tasks; class Program { const int _Total = int.MaxValue; static long _Count = 0; public static void Main() { Task task = Task.Factory.StartNew(Decrement); // Increment for (int i = 0; i < _Total; i++) { } task.Wait(); Console.WriteLine("Count = {0}", _Count); } static void Decrement() { for (int i = 0; i < _Total; i++) { readonly static object _Sync = new object