码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-07-26 00:59:56      阅读:464      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   os   2014   for   

项目中遇到一个问题如题,于是做了个小实验,发现在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     }

运行如下:

bubuko.com,布布扣

lock中使用迭代返回yield return是否会释放锁?,布布扣,bubuko.com

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

标签:style   blog   http   color   使用   os   2014   for   

原文地址:http://www.cnblogs.com/scm-forever/p/3868756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!