Code:
/ 4.0 / 4.0 / DEVDIV_TFS / Dev10 / Releases / RTMRel / ndp / cdf / src / WCF / System.ServiceModel.Activation / System / ServiceModel / Activation / ServiceMemoryGates.cs / 1305376 / ServiceMemoryGates.cs
//---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //--------------------------------------------------------------------------- namespace System.ServiceModel.Activation { using System.ComponentModel; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.ServiceModel.Channels; using System.Threading; static class ServiceMemoryGates { [Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical helper methods to check memory status." + "Allocates unmanaged resources, can only be called with admin-specified value.")] [SecurityCritical] internal static void Check(int minFreeMemoryPercentage) { // Boundary check percentage, if out of bounds Gate is turned off. // 0 is defined as disabled. Configuration defines 99 as max allowed so we disable // if we receive something out of range if (minFreeMemoryPercentage < 1 || minFreeMemoryPercentage > 99) { return; } UnsafeNativeMethods.MEMORYSTATUSEX memoryStatus = new UnsafeNativeMethods.MEMORYSTATUSEX(); GetGlobalMemoryStatus(ref memoryStatus); ulong threshold = memoryStatus.ullTotalPageFile / 100 * (ulong)minFreeMemoryPercentage; if (memoryStatus.ullAvailPageFile < threshold) { // Yield this thread -- this will also ensure that we have a full time slice when we // do our alloc/free Thread.Sleep(0); // Commit 1.5 times of the threshold. This should force the page file to grow, if // possible. (GlobalMemoryStatusEx only returns information about the current pagefile, // not about the maximum pagefile.) uint sizeToAlloc = 0; if (threshold < (ulong)int.MaxValue) { sizeToAlloc = (uint)threshold / 2 * 3; } if (sizeToAlloc > 0) { ForcePageFileToGrow(sizeToAlloc); GetGlobalMemoryStatus(ref memoryStatus); threshold = memoryStatus.ullTotalPageFile / 100 * (ulong)minFreeMemoryPercentage; } if (memoryStatus.ullAvailPageFile < threshold) { throw FxTrace.Exception.AsError(new InsufficientMemoryException( SR.Hosting_MemoryGatesCheckFailed(memoryStatus.ullAvailPageFile, minFreeMemoryPercentage))); } } } [Fx.Tag.SecurityNote(Critical = "Uses UnsafeNativeMethods, caller must guard parameter.")] [SecurityCritical] static void ForcePageFileToGrow(uint sizeToAlloc) { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { // We don't care if this actually succeeds or not, we are just trying to grow the page // file. IntPtr ptr = UnsafeNativeMethods.VirtualAlloc(IntPtr.Zero, (UIntPtr)sizeToAlloc, UnsafeNativeMethods.MEM_COMMIT, (uint)UnsafeNativeMethods.PAGE_READWRITE); if (ptr != IntPtr.Zero) { UnsafeNativeMethods.VirtualFree(ptr, (UIntPtr)sizeToAlloc, UnsafeNativeMethods.MEM_DECOMMIT); } } } [Fx.Tag.SecurityNote(Critical = "Uses UnsafeNativeMethods to fetch memory status structure, caller must not leak it.")] [SecurityCritical] static void GetGlobalMemoryStatus(ref UnsafeNativeMethods.MEMORYSTATUSEX memoryStatus) { memoryStatus.dwLength = (uint)Marshal.SizeOf(typeof(UnsafeNativeMethods.MEMORYSTATUSEX)); if (!UnsafeNativeMethods.GlobalMemoryStatusEx(ref memoryStatus)) { int error = Marshal.GetLastWin32Error(); // Treat as the worst case. throw FxTrace.Exception.AsError( new InvalidOperationException(SR.Hosting_GetGlobalMemoryFailed, new Win32Exception(error))); } } } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. //---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //--------------------------------------------------------------------------- namespace System.ServiceModel.Activation { using System.ComponentModel; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.ServiceModel.Channels; using System.Threading; static class ServiceMemoryGates { [Fx.Tag.SecurityNote(Critical = "Uses SecurityCritical helper methods to check memory status." + "Allocates unmanaged resources, can only be called with admin-specified value.")] [SecurityCritical] internal static void Check(int minFreeMemoryPercentage) { // Boundary check percentage, if out of bounds Gate is turned off. // 0 is defined as disabled. Configuration defines 99 as max allowed so we disable // if we receive something out of range if (minFreeMemoryPercentage < 1 || minFreeMemoryPercentage > 99) { return; } UnsafeNativeMethods.MEMORYSTATUSEX memoryStatus = new UnsafeNativeMethods.MEMORYSTATUSEX(); GetGlobalMemoryStatus(ref memoryStatus); ulong threshold = memoryStatus.ullTotalPageFile / 100 * (ulong)minFreeMemoryPercentage; if (memoryStatus.ullAvailPageFile < threshold) { // Yield this thread -- this will also ensure that we have a full time slice when we // do our alloc/free Thread.Sleep(0); // Commit 1.5 times of the threshold. This should force the page file to grow, if // possible. (GlobalMemoryStatusEx only returns information about the current pagefile, // not about the maximum pagefile.) uint sizeToAlloc = 0; if (threshold < (ulong)int.MaxValue) { sizeToAlloc = (uint)threshold / 2 * 3; } if (sizeToAlloc > 0) { ForcePageFileToGrow(sizeToAlloc); GetGlobalMemoryStatus(ref memoryStatus); threshold = memoryStatus.ullTotalPageFile / 100 * (ulong)minFreeMemoryPercentage; } if (memoryStatus.ullAvailPageFile < threshold) { throw FxTrace.Exception.AsError(new InsufficientMemoryException( SR.Hosting_MemoryGatesCheckFailed(memoryStatus.ullAvailPageFile, minFreeMemoryPercentage))); } } } [Fx.Tag.SecurityNote(Critical = "Uses UnsafeNativeMethods, caller must guard parameter.")] [SecurityCritical] static void ForcePageFileToGrow(uint sizeToAlloc) { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { // We don't care if this actually succeeds or not, we are just trying to grow the page // file. IntPtr ptr = UnsafeNativeMethods.VirtualAlloc(IntPtr.Zero, (UIntPtr)sizeToAlloc, UnsafeNativeMethods.MEM_COMMIT, (uint)UnsafeNativeMethods.PAGE_READWRITE); if (ptr != IntPtr.Zero) { UnsafeNativeMethods.VirtualFree(ptr, (UIntPtr)sizeToAlloc, UnsafeNativeMethods.MEM_DECOMMIT); } } } [Fx.Tag.SecurityNote(Critical = "Uses UnsafeNativeMethods to fetch memory status structure, caller must not leak it.")] [SecurityCritical] static void GetGlobalMemoryStatus(ref UnsafeNativeMethods.MEMORYSTATUSEX memoryStatus) { memoryStatus.dwLength = (uint)Marshal.SizeOf(typeof(UnsafeNativeMethods.MEMORYSTATUSEX)); if (!UnsafeNativeMethods.GlobalMemoryStatusEx(ref memoryStatus)) { int error = Marshal.GetLastWin32Error(); // Treat as the worst case. throw FxTrace.Exception.AsError( new InvalidOperationException(SR.Hosting_GetGlobalMemoryFailed, new Win32Exception(error))); } } } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007.
Link Menu
This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- Helper.cs
- ObjectItemCollection.cs
- BindableAttribute.cs
- ListItemConverter.cs
- ObjectDataSourceFilteringEventArgs.cs
- HttpRequestCacheValidator.cs
- EntityFunctions.cs
- BamlLocalizableResource.cs
- SystemUnicastIPAddressInformation.cs
- ResolvedKeyFrameEntry.cs
- ClosureBinding.cs
- StoreAnnotationsMap.cs
- BitmapEffectInput.cs
- ProfilePropertyNameValidator.cs
- XamlClipboardData.cs
- StylusPlugInCollection.cs
- MostlySingletonList.cs
- SafeNativeMethods.cs
- KnownTypeDataContractResolver.cs
- InvalidEnumArgumentException.cs
- HttpCapabilitiesBase.cs
- PcmConverter.cs
- ToolStripRenderEventArgs.cs
- DataGridItem.cs
- XmlSchemaImporter.cs
- ListControlConvertEventArgs.cs
- UnicodeEncoding.cs
- PasswordPropertyTextAttribute.cs
- DeferredSelectedIndexReference.cs
- LayoutTableCell.cs
- Stroke2.cs
- HostingEnvironment.cs
- HandleCollector.cs
- CodeDomLocalizationProvider.cs
- PolicyLevel.cs
- CodeComment.cs
- AesManaged.cs
- TargetConverter.cs
- ListViewCancelEventArgs.cs
- MessageQueue.cs
- PipeConnection.cs
- WmlValidationSummaryAdapter.cs
- XmlNamespaceMappingCollection.cs
- TextureBrush.cs
- entityreference_tresulttype.cs
- CreateUserWizardStep.cs
- SafeProcessHandle.cs
- InkCanvasSelectionAdorner.cs
- GB18030Encoding.cs
- FixedSOMTextRun.cs
- WeakRefEnumerator.cs
- TemplateEditingFrame.cs
- ValueUnavailableException.cs
- TableRowCollection.cs
- TraceListeners.cs
- DragEventArgs.cs
- FunctionUpdateCommand.cs
- DataRowChangeEvent.cs
- BamlWriter.cs
- StrokeRenderer.cs
- FederatedMessageSecurityOverHttpElement.cs
- CodeRegionDirective.cs
- SafeRsaProviderHandle.cs
- Application.cs
- ImageAttributes.cs
- NamedObject.cs
- WebException.cs
- HtmlWindowCollection.cs
- VariableBinder.cs
- ChangePasswordAutoFormat.cs
- SqlTransaction.cs
- DBNull.cs
- SafeLibraryHandle.cs
- TriggerCollection.cs
- IndexOutOfRangeException.cs
- StoreAnnotationsMap.cs
- AnalyzedTree.cs
- XmlAtomicValue.cs
- VersionedStream.cs
- CustomErrorCollection.cs
- ListChangedEventArgs.cs
- BindableAttribute.cs
- ImportContext.cs
- HttpProfileBase.cs
- TimeZone.cs
- TraceContext.cs
- CookieProtection.cs
- TypedDataSetSchemaImporterExtension.cs
- ProtocolsConfigurationHandler.cs
- EntityPropertyMappingAttribute.cs
- Int32RectValueSerializer.cs
- MonthCalendar.cs
- LinqDataSourceStatusEventArgs.cs
- LoginName.cs
- OpCopier.cs
- SoapAttributeOverrides.cs
- EnumerableRowCollectionExtensions.cs
- HandlerWithFactory.cs
- ObjectDataSourceStatusEventArgs.cs
- Property.cs