代码级数据库排他锁的实现

C#下,实现代码级数据库表(多个数据库)排他锁:

可以使用lock关键字 ==> 唯一object对象的获取(GetSycObject)

GetSycObject的实现:

1、由数据库ID和表ID结合创建标识ID。

2、使用静态的Dictionary<int, Object>类型变量存放表对应的object。

3、GetSycObject方法本身的排他。

总结以上,排他锁工具类代码如下:

1 public static class DBSynchronousHelper
2 {
3
4 private const int INCREASE = 1000;
5 /// <summary>
6 /// Synchronized object repository.
7 /// </summary>
8   private static Dictionary<int, Object> syncRepository = new Dictionary<int, object>();
9
10
11 /// <summary>
12 /// Get synchronized object from repository.
13 /// </summary>
14 /// <param name="databaseID"></param>
15 /// <param name="tableID"></param>
16 /// <returns>Synchronized object accroding to XX table(tableID) in XX DataBase(databaseID)</returns>
17   public static Object GetSyncObject(int databaseID, int tableID)
18 {
19 int key = databaseID * INCREASE + tableID;
20 lock (syncRepository)
21 {
22 Object syncObject = null;
23
24 if (!syncRepository.TryGetValue(key, out syncObject))
25 {
26 syncObject = new Object();
27 syncRepository.Add(key, syncObject);
28 }
29
30 return syncObject;
31 }
32
33
34 }
35
36
37 /// <summary>
38 /// SampleLock
39 /// </summary>
40 /// <param name="databaseID"></param>
41 /// <param name="tableid"></param>
42 public static void SampleLock(int databaseID, int tableid)
43 {
44 try
45 {
46 lock (DBSynchronousHelper.GetSyncObject(databaseID, tableid))
47 {
48 //do write to XX table of XX DB;
49 }
50 }
51 catch (Exception e)
52 {
53 throw e;
54 }
55
56 }
57 }

posted @ 2011-02-24 16:33  freezym  阅读(1060)  评论(0编辑  收藏  举报