-
Notifications
You must be signed in to change notification settings - Fork 935
/
Copy pathColumnNameCache.cs
56 lines (50 loc) · 1.2 KB
/
ColumnNameCache.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System.Collections.Generic;
using System.Threading;
namespace NHibernate.AdoNet
{
/// <summary> Implementation of ColumnNameCache. Thread safe. </summary>
public class ColumnNameCache
{
private readonly ReaderWriterLockSlim _cacheLock = new ReaderWriterLockSlim();
private readonly Dictionary<string, int> _columnNameToIndexCache;
public ColumnNameCache(int columnCount)
{
// should *not* need to grow beyond the size of the total number of columns in the rs
_columnNameToIndexCache = new Dictionary<string, int>(columnCount);
}
public int GetIndexForColumnName(string columnName, ResultSetWrapper rs)
{
int index;
if (!TryRead(columnName, out index))
{
index = rs.Target.GetOrdinal(columnName);
Insert(columnName, index);
}
return index;
}
private bool TryRead(string key, out int value)
{
_cacheLock.EnterReadLock();
try
{
return _columnNameToIndexCache.TryGetValue(key, out value);
}
finally
{
_cacheLock.ExitReadLock();
}
}
private void Insert(string key, int value)
{
_cacheLock.EnterWriteLock();
try
{
_columnNameToIndexCache[key] = value;
}
finally
{
_cacheLock.ExitWriteLock();
}
}
}
}