download _localdatastoremgr.cs
Language: C#
Copyright: (c) 2006 Microsoft Corporation. All rights reserved.
LOC: 213
Project Info
Rotor IL Logger(rotorillogger)
Server: CodePlex1
Type: svn
...ger\svn\clr\src\bcl\system\
   __filters.cs
   __hresults.cs
   _localdatastore.cs
   _localdatastoremgr.cs
   ...ssviolationexception.cs
   activationarguments.cs
   activator.cs
   appdomain.cs
   appdomainattributes.cs
   appdomainmanager.cs
   appdomainsetup.cs
   ...ainunloadedexception.cs
   applicationactivator.cs
   applicationexception.cs
   applicationid.cs
   argiterator.cs
   argumentexception.cs
   argumentnullexception.cs
   ...toutofrangeexception.cs
   arithmeticexception.cs
   array.cs
   arraysegment.cs
   ...ypemismatchexception.cs
   asynccallback.cs
   attribute.cs
   attributetargets.cs
   attributeusageattribute.cs
   badimageformatexception.cs
   bcldebug.cs
   bitconverter.cs
   boolean.cs
   buffer.cs
   byte.cs
   ...adappdomainexception.cs
   cfgparser.cs
   char.cs
   charenumerator.cs
   clscompliantattribute.cs
   cominterfaces.cs
   compatibilityflags.cs
   ...usmethodframegeneric.cs
   console.cs
   consolecanceleventargs.cs
   consolespecialkey.cs
   contextboundobject.cs
   contextmarshalexception.cs
   contextstaticattribute.cs
   convert.cs
   currency.cs
   currenttimezone.cs
   datamisalignedexception.cs
   datetime.cs
   datetimekind.cs
   dayofweek.cs
   dbnull.cs
   decimal.cs
   defaultbinder.cs
   delegate.cs
   ...eserializationholder.cs
   dividebyzeroexception.cs
   dllnotfoundexception.cs
   double.cs
   ...ewaitobjectexception.cs
   empty.cs
   ...intnotfoundexception.cs
   enum.cs
   environment.cs
   eventargs.cs
   eventhandler.cs
   exception.cs
   ...utionengineexception.cs
   fieldaccessexception.cs
   flagsattribute.cs
   formatexception.cs
   gc.cs
   guid.cs
   iappdomain.cs
   iappdomainsetup.cs
   iasyncresult.cs
   icloneable.cs
   icomparable.cs
   iconvertible.cs
   icustomformatter.cs
   idisposable.cs
   iequatable.cs
   iformatprovider.cs
   iformattable.cs
   ...xoutofrangeexception.cs
   ...cientmemoryexception.cs
   int16.cs
   int32.cs
   int64.cs
   internal.cs
   intptr.cs
   invalidcastexception.cs
   ...idoperationexception.cs
   invalidprogramexception.cs
   iserviceobjectprovider.cs
   marshalbyrefobject.cs
   math.cs
   mda.cs
   memberaccessexception.cs
   methodaccessexception.cs
   midpointrounding.cs
   missingfieldexception.cs
   missingmemberexception.cs
   missingmethodexception.cs
   multicastdelegate.cs
   ...otsupportedexception.cs
   ndirectmethodframeex.cs
   nonserializedattribute.cs
   ...initenumberexception.cs
   notimplementedexception.cs
   notsupportedexception.cs
   nullable.cs
   nullreferenceexception.cs
   number.cs
   object.cs
   objectdisposedexception.cs
   obsoleteattribute.cs
   oleautbinder.cs
   operatingsystem.cs
   ...ioncanceledexception.cs
   outofmemoryexception.cs
   overflowexception.cs
   paramarrayattribute.cs
   parsenumbers.cs
   platformid.cs
   ...otsupportedexception.cs
   random.cs
   rankexception.cs
   resid.cs
   rttype.cs
   runtimeargumenthandle.cs
   runtimehandles.cs
   sbyte.cs
   serializableattribute.cs
   sharedstatics.cs
   single.cs
   stackoverflowexception.cs
   string.cs
   stringcomparer.cs
   stringcomparison.cs
   stringfreezingattribute.cs
   systemexception.cs
   threadattributes.cs
   threadstaticattribute.cs
   throwhelper.cs
   timeoutexception.cs
   timespan.cs
   timezone.cs
   type.cs
   typecode.cs
   typedreference.cs
   ...tializationexception.cs
   typeloadexception.cs
   typeunloadedexception.cs
   uint16.cs
   uint32.cs
   uint64.cs
   uintptr.cs
   ...rizedaccessexception.cs
   ...edexceptioneventargs.cs
   ...xceptioneventhandler.cs
   ...yserializationholder.cs
   unsafecharbuffer.cs
   valuetype.cs
   variant.cs
   version.cs
   void.cs
   weakreference.cs
   ...gnorememberattribute.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// ==++==
// 
//   
//    Copyright (c) 2006 Microsoft Corporation.  All rights reserved.
//   
//    The use and distribution terms for this software are contained in the file
//    named license.txt, which can be found in the root of this distribution.
//    By using this software in any fashion, you are agreeing to be bound by the
//    terms of this license.
//   
//    You must not remove this notice, or any other, from this software.
//   
// 
// ==--==
/*=============================================================================
**
** Class: LocalDataStoreMgr
**
**
** Purpose: Class that manages stores of local data. This class is used in 
**          cooperation with the LocalDataStore class.
**
**
=============================================================================*/
namespace System {
    
    using System;
    using System.Collections;
    using System.Threading;
    using System.Runtime.CompilerServices;

	// This is a cheesy internal helper class that is used to make sure memory
	// is actually being accessed and not some cached copy of a field in a
	// register.
	// WARNING: If we every do type analysis to eliminate virtual functions,
	// this will break.
	// This class will not be marked serializable
	internal class LdsSyncHelper
	{
		internal virtual int Get(ref int slot)
		{
			return slot;
		}
	}

	// This class is an encapsulation of a slot so that it is managed in a secure fashion.
	// It is constructed by the LocalDataStoreManager, holds the slot and the manager
	// and cleans up when it is finalized.
	// This class will not be marked serializable
[System.Runtime.InteropServices.ComVisible(true)]
	public sealed class LocalDataStoreSlot
	{
		private static LdsSyncHelper m_helper = new LdsSyncHelper();

		private LocalDataStoreMgr m_mgr;
		private int m_slot;

		// Construct the object to encapsulate the slot.
		internal LocalDataStoreSlot(LocalDataStoreMgr mgr, int slot)
		{
			m_mgr = mgr;
			m_slot = slot;
		}

		// Accessors for the two fields of this class.
		internal LocalDataStoreMgr Manager
		{
			get
			{
				return m_mgr;
			}
		}
		internal int Slot
		{
			get
			{
				return m_slot;
			}
		}

		// This is used to make sure we are actually reading and writing to
		// memory to fetch the slot (rather than possibly using a value
		// cached in a register).
		internal bool IsValid()
		{
			return m_helper.Get(ref m_slot) != -1;
		}

		// Release the slot reserved by this object when this object goes away.
		// There is  a race condition that can happen in the face of
		// resurrection where another thread is fetching values or assigning
		// while the finalizer thread is here.  We are counting on the fact
		// that code that fetches values calls IsValid after fetching a value
		// and before giving it to anyone.  See LocalDataStore for the other 
		// half of this.  We are also counting on code that sets values locks
		// the manager.
        ~LocalDataStoreSlot()
		{
			int slot = m_slot;

			// This lock fixes synchronization with the assignment of values.
            bool tookLock = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                Monitor.ReliableEnter(m_mgr, ref tookLock);
				// Mark the slot as free.
				m_slot = -1;

				m_mgr.FreeDataSlot(slot);
			}
            finally {
                if (tookLock)
                    Monitor.Exit(m_mgr);
            }
		}
	}

	// This class will not be marked serializable
    internal class LocalDataStoreMgr
    {
    	private const byte DataSlotOccupied				= 0x01;

    	private const int InitialSlotTableSize			= 64;
    	private const int SlotTableDoubleThreshold		= 512;
    	private const int LargeSlotTableSizeIncrease	= 128;
    
        /*=========================================================================
        ** Create a data store to be managed by this manager and add it to the
		** list. The initial size of the new store matches the number of slots
		** allocated in this manager.
        =========================================================================*/
    	public LocalDataStore CreateLocalDataStore()
    	{
        	// Create a new local data store.
        	LocalDataStore Store = new LocalDataStore(this, m_SlotInfoTable.Length);
        		
            bool tookLock = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                Monitor.ReliableEnter(this, ref tookLock);
        		// Add the store to the array list and return it.
        		m_ManagedLocalDataStores.Add(Store);
        	}
            finally {
                if (tookLock)
                    Monitor.Exit(this);
            }
       		return Store;
	    }

        /*=========================================================================
		 * Remove the specified store from the list of managed stores..
        =========================================================================*/
    	public void DeleteLocalDataStore(LocalDataStore store)
		{
            bool tookLock = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                Monitor.ReliableEnter(this, ref tookLock);
        		// Remove the store to the array list and return it.
        		m_ManagedLocalDataStores.Remove(store);
        	}
            finally {
                if (tookLock)
                    Monitor.Exit(this);
            }
		}

        /*=========================================================================
        ** Allocates a data slot by finding an available index and wrapping it
		** an object to prevent clients from manipulating it directly, allowing us
		** to make assumptions its integrity.
        =========================================================================*/
    	public LocalDataStoreSlot AllocateDataSlot()
    	{
            bool tookLock = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                Monitor.ReliableEnter(this, ref tookLock);
        		int i;		
        		LocalDataStoreSlot slot;

        		// Retrieve the current size of the table.
        		int SlotTableSize = m_SlotInfoTable.Length;

				// Check if there are any slots left.
				if (m_FirstAvailableSlot < SlotTableSize)
				{
					// Save the first available slot.
					slot = new LocalDataStoreSlot(this, m_FirstAvailableSlot);
       				m_SlotInfoTable[m_FirstAvailableSlot] = DataSlotOccupied;

					// Find the next available slot.
					for (i=m_FirstAvailableSlot+1; i < SlotTableSize; ++i)
	        			if (0 == (m_SlotInfoTable[i] & DataSlotOccupied))
							break;

					// Save the new "first available slot".
					m_FirstAvailableSlot = i;

					// Return the slot index.
					return slot;
				}

        		// The table is full so we need to increase its size.
        		int NewSlotTableSize;
        		if (SlotTableSize < SlotTableDoubleThreshold)
        		{
        			// The table is still relatively small so double it.
        			NewSlotTableSize = SlotTableSize * 2;
        		}
        		else
        		{
        			// The table is relatively large so simply increase its size by a given amount.
        			NewSlotTableSize = SlotTableSize + LargeSlotTableSizeIncrease;
        		}

        		// Allocate the new slot info table.
        		byte[] NewSlotInfoTable = new byte[NewSlotTableSize];

        		// Copy the old array into the new one.
        		Array.Copy(m_SlotInfoTable, NewSlotInfoTable, SlotTableSize);
        		m_SlotInfoTable = NewSlotInfoTable;

        		// SlotTableSize is the index of the first empty slot in the expanded table.
				slot = new LocalDataStoreSlot(this, SlotTableSize);
        		m_SlotInfoTable[SlotTableSize] = DataSlotOccupied;
				m_FirstAvailableSlot = SlotTableSize + 1;

        		// Return the selected slot
        		return slot;			
        	}
            finally {
                if (tookLock)
                    Monitor.Exit(this);
            }
	    }
    	
        /*=========================================================================
		** Allocate a slot and associate a name with it.
        =========================================================================*/
    	public LocalDataStoreSlot AllocateNamedDataSlot(String name)
    	{
            bool tookLock = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                Monitor.ReliableEnter(this, ref tookLock);
        		// Allocate a normal data slot.
				LocalDataStoreSlot slot = AllocateDataSlot();

        		// Insert the association between the name and the data slot number
				// in the hash table.
        		m_KeyToSlotMap.Add(name, slot);
        		return slot;
        	}
            finally {
                if (tookLock)
                    Monitor.Exit(this);
            }
		}

        /*=========================================================================
		** Retrieve the slot associated with a name, allocating it if no such
		** association has been defined.
        =========================================================================*/
    	public LocalDataStoreSlot GetNamedDataSlot(String name)
    	{
            bool tookLock = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                Monitor.ReliableEnter(this, ref tookLock);
        		// Lookup in the hashtable to try find a slot for the name.
        		LocalDataStoreSlot slot = (LocalDataStoreSlot) m_KeyToSlotMap[name];
        		
        		// If the name is not yet in the hashtable then add it.
        		if (null == slot)
        			return AllocateNamedDataSlot(name);
        		
        		// The name was in the hashtable so return the associated slot.
        		return slot;
        	}
            finally {
                if (tookLock)
                    Monitor.Exit(this);
            }
		}

        /*=========================================================================
		** Eliminate the association of a name with a slot.  The actual slot will
		** be reclaimed when the finalizer for the slot object runs.
        =========================================================================*/
    	public void FreeNamedDataSlot(String name)
    	{
            bool tookLock = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                Monitor.ReliableEnter(this, ref tookLock);
        		// Remove the name slot association from the hashtable.
        		m_KeyToSlotMap.Remove(name);
        	}
            finally {
                if (tookLock)
                    Monitor.Exit(this);
            }
		}

        /*=========================================================================
        ** Free's a previously allocated data slot on ALL the managed data stores.
        =========================================================================*/
    	internal void FreeDataSlot(int slot)
    	{
            bool tookLock = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                Monitor.ReliableEnter(this, ref tookLock);
        		// Go thru all the managed stores and set the data on the specified slot to 0.
        		for (int i=0; i < m_ManagedLocalDataStores.Count; i++)
        		{
        			((LocalDataStore)m_ManagedLocalDataStores[i]).SetDataInternal(
        			                                                  slot, 
        			                                                  null, 
        			                                                  false);
                }        			                                                    
    			        		
        		// Mark the slot as being no longer occupied. 
        		m_SlotInfoTable[slot] = 0;
				if (slot < m_FirstAvailableSlot)
					m_FirstAvailableSlot = slot;
        	}
            finally {
                if (tookLock)
                    Monitor.Exit(this);
            }
	    }

        /*=========================================================================
        ** Return the number of allocated slots in this manager.
        =========================================================================*/
	    public void ValidateSlot(LocalDataStoreSlot slot)
	    {
            // Make sure the slot was allocated for this store.
	        if (slot==null || slot.Manager != this)
                throw new ArgumentException(Environment.GetResourceString("Argument_ALSInvalidSlot"));
        }

        /*=========================================================================
        ** Return the number of allocated slots in this manager.
        =========================================================================*/
	    internal int GetSlotTableLength()
	    {
	            return m_SlotInfoTable.Length;
        }

    	private byte[] m_SlotInfoTable = new byte[InitialSlotTableSize];
		private int m_FirstAvailableSlot = 0;
    	private ArrayList m_ManagedLocalDataStores = new ArrayList();
    	private Hashtable m_KeyToSlotMap = new Hashtable();
    }
}

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us