首页 > 代码库 > 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 }
运行如下:
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。