C# lock内部新开线程,新开的线程不占有lock, lock对新开的线程无效,造成假锁。
using System; using System.Collections.Generic; using System.Threading; namespace SynchronizeDemo { class Program { private static readonly List<string> Names = new List<string>(); private static readonly object SyncLock = new object(); private const string MyName = "尹永贤"; static void Main() { lock (SyncLock) { if (!Names.Contains(MyName)) { AddSynchronizeName(); } } lock (SyncLock) { if (!Names.Contains(MyName)) { AddName(); } } Thread.Sleep(5000); lock (SyncLock) { foreach (var name in Names) { Console.WriteLine(name); } } Console.ReadKey(); } private static void AddName() { Names.Add(MyName); } private static void AddSynchronizeName() { /*/ //1.常规操作 Names.Add(MyName); /**/ /**/ //2.异步操作 var thread = new Thread(() => { Thread.Sleep(2000); Names.Add(MyName); }) { IsBackground = true }; thread.Start(); /**/ } } }
新开线程的结果和常规的结果不一样,也就失去了同步的意义。