首页 > 代码库 > lock中使用迭代返回yield return是否会释放锁?

lock中使用迭代返回yield return是否会释放锁?

项目中遇到一个问题如题,于是做了个小实验,发现在lock中yield return并不会释放该lock,直到整个迭代器完全执行完或者yield break后才会释放lock。

 1 class Program 2     { 3         static object mylock = new object(); 4         static long index = 0xff; 5              6         static void Main(string[] args) 7         { 8             System.Threading.Thread t1 = new System.Threading.Thread( 9                 () =>10                 {11                     foreach (long l in method1())12                     {13                         for (int i = 0; i < 0xff;i++ )14                             Console.WriteLine("\t" + i.ToString("X2"));15                         Console.WriteLine(l.ToString("X4"));16                     }17                 });18             t1.IsBackground = true;19             t1.Start();20 21 22             System.Threading.Thread t2 = new System.Threading.Thread(23                 () =>24                 {25                     for (int i = 0; i < 100; i++)26                     {27                         lock (mylock)28                         {29                             Console.WriteLine("\t\t\tI‘m in the lock!");30                         }31                     }32                 });33             t2.IsBackground=true;34             t2.Start();35 36 37             Console.ReadKey();38         }39 40         static IEnumerable<long> method1()41         {42             lock (mylock)43             {44                 for (long i = 0; i < index; i++)45                 {46                     yield return i;47                 }48             }49         }50     }

运行如下: