sailing

Everything...

使用.net-Synchronized属性进行静态方法的同步

使用.net属性进行静态方法的同步

本文介绍使用.net得Synchronized属性实现线程的同步.
Synchronized毋庸置疑,可以方便的实现instance level的方法同步,但是是否同样适用于static方法呢?本文写了下面的代码进行验证。结果令人满意,确实可以实现静态方法的同步。
 1 
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Text;
 5 using System.Runtime.CompilerServices;
 6 using System.Threading;
 7 
 8 namespace TestN
 9 {
10     class Test
11     {
12         public static void Main()
13         {
14             new Thread(Add).Start();
15             Add2();
16         }
17 
18         [MethodImpl(MethodImplOptions.Synchronized)]
19         public static void Add()
20         {
21             Console.WriteLine("1");
22             Console.ReadLine();
23         }
24 
25         [MethodImpl(MethodImplOptions.Synchronized)]
26         public static void Add2()
27         {
28             Console.WriteLine("2");
29             Console.ReadLine();
30         }
31     }
32 }

posted on 2008-04-13 03:45  乌生鱼汤  阅读(1377)  评论(1编辑  收藏  举报

导航