Code:
/ WCF / WCF / 3.5.30729.1 / untmp / Orcas / SP / ndp / cdf / src / WCF / infocard / Service / managed / Microsoft / InfoCards / LifetimeMonitor.cs / 1 / LifetimeMonitor.cs
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- // // Presharp uses the c# pragma mechanism to supress its warnings. // These are not recognised by the base compiler so we need to explictly // disable the following warnings. See http://winweb/cse/Tools/PREsharp/userguide/default.asp // for details. // #pragma warning disable 1634, 1691 // unknown message, unknown pragma namespace Microsoft.InfoCards { using System; using Microsoft.Win32; using System.ServiceProcess; using System.Timers; using Microsoft.InfoCards.Diagnostics; using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace; // // Summary: // Manages the lifetime of the service, // Watches for incoming and outgoing // requests and shuts down the service after a certain period of inactivity. // class LifeTimeMonitor { // // How long we wait with no activity before shutting down. // const int DefaultShutdownInterval = 60 * 60 * 1000 ; // in milliseconds. // // The minimum wait we can define. // const int MinimumShutdownInterval = 60 * 1000; // in milliseconds // // Registry value to override the shutdown time. // const string ServiceIdleTimeValue = "ServiceIdleTime"; // // The number of active clients. // int m_activeCount = 0; // // Are we in the process of shutting down // bool m_isShuttingDown = false; // // The shutdown timer. // System.Timers.Timer m_shutdownTimer; object m_syncRoot = new Object(); public LifeTimeMonitor() { // // Read the idle time from the registry. // int shutdownInterval = DefaultShutdownInterval; using( SystemIdentity system = new SystemIdentity( false ) ) { using( RegistryKey rk = Registry.LocalMachine.OpenSubKey( InfoCardConstants.RegistryKey, false ) ) { if( null != rk ) { object idleTime = rk.GetValue( ServiceIdleTimeValue , DefaultShutdownInterval ); if( idleTime is int && (int)idleTime >= MinimumShutdownInterval ) { shutdownInterval = (int)idleTime; } } } } IDT.TraceDebug( "LIFETIME: Setting service idle time to {0} seconds\n", shutdownInterval / 1000.0 ); m_activeCount = 0; m_shutdownTimer = new System.Timers.Timer( shutdownInterval ); m_shutdownTimer.Elapsed += this.OnShutdown; m_shutdownTimer.AutoReset = false; m_isShuttingDown = false; StartShutdownTimer(); } // // Summary: // Register that a client request has entered the system. // Stops the idle timer if this is the first request in. // public void AddClient() { lock( m_syncRoot ) { IDT.Assert( m_activeCount >= 0, "incorrect active count" ); // // We could have been blocked on a shutdown. If so, then throw the service busy // exception // if( m_isShuttingDown ) { IDT.TraceDebug( "LIFETIME: Shutdown in progress, aborting incoming client request" ); throw IDT.ThrowHelperError( new ServiceBusyException() ); } m_activeCount++; IDT.TraceDebug( "LIFETIME: Adding client - active count is now {0}", m_activeCount ); if( 1 == m_activeCount ) { IDT.TraceDebug( "LIFETIME: Shutdown timer detecting first incoming client" ); StopShutdownTimer(); } } } // // Summary: // Called when a client request is disposed. // Starts the idle timer if there are no outstanding requests. // public void RemoveClient() { lock( m_syncRoot ) { IDT.Assert( m_activeCount > 0, "invalid active count" ); IDT.TraceDebug( "LIFETIME: Removing client {0}", m_activeCount ); m_activeCount--; if( m_activeCount == 0 ) { IDT.TraceDebug( "LIFETIME: Shutdown timer becoming active" ); StartShutdownTimer(); } } } // // Summary: // Callback function fired when the inactivity period has elapsed. // Parameters // Unused. // private void OnShutdown( object sender, ElapsedEventArgs args ) { lock( m_syncRoot ) { // // Conceivably we could have been waiting on someone adding a client. Exit if so. // // There is an additional race here that we don't handle: // A caller could have called AddClient() and ReleaseClient() in between our // being sent the shutdown event and acquiring the lock, but this would only cause an immediate // shutdown following that client request and will not break things functionally. // We could extend the remove code to record the timestamp of when the last remove // occurred, but this is overkill as the extended lifetime of our // requests make this very unlikely to happen. // if( m_activeCount > 0 ) { IDT.TraceDebug( "LIFETIME: Detected race with incoming request. Aborting service shutdown" ); return; } IDT.TraceDebug( "LIFETIME: Shutting down the service due to idle timeout" ); m_shutdownTimer.Enabled = false; // // Prevent any more incoming callers. // m_isShuttingDown = true; // // Audit that we are shutting down due to idle timeout. // IDT.Audit( EventCode.AUDIT_SERVICE_IDLE_STOP ); } using( SystemIdentity system = new SystemIdentity( false ) ) { new ServiceController( InfoCardService.FullServiceName ).Stop(); } } private void StartShutdownTimer() { m_shutdownTimer.Start(); } private void StopShutdownTimer() { m_shutdownTimer.Stop(); } } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. // Copyright (c) Microsoft Corporation. All rights reserved.
Link Menu
This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- SymLanguageVendor.cs
- CultureSpecificStringDictionary.cs
- RowToFieldTransformer.cs
- PenCursorManager.cs
- ForeignKeyConstraint.cs
- OletxTransactionManager.cs
- JsonDeserializer.cs
- BasePropertyDescriptor.cs
- DetailsViewDeletedEventArgs.cs
- ACE.cs
- ExtensionQuery.cs
- NestPullup.cs
- BinaryWriter.cs
- HeaderUtility.cs
- InvariantComparer.cs
- CodeDirectiveCollection.cs
- FlowDocumentPage.cs
- OracleString.cs
- WebSysDescriptionAttribute.cs
- ProfilePropertyMetadata.cs
- ObjectItemCollectionAssemblyCacheEntry.cs
- QuotedPrintableStream.cs
- SafeNativeMemoryHandle.cs
- InstancePersistenceException.cs
- PathData.cs
- QilPatternFactory.cs
- TableLayoutSettingsTypeConverter.cs
- ScrollChrome.cs
- OdbcParameterCollection.cs
- StsCommunicationException.cs
- TextCompositionManager.cs
- GradientSpreadMethodValidation.cs
- BamlVersionHeader.cs
- BindableAttribute.cs
- DSASignatureDeformatter.cs
- RenderTargetBitmap.cs
- DataGridViewTopLeftHeaderCell.cs
- UriExt.cs
- RSAPKCS1KeyExchangeDeformatter.cs
- RegistrySecurity.cs
- Label.cs
- SiteMapNode.cs
- RSACryptoServiceProvider.cs
- InkCanvasAutomationPeer.cs
- StaticFileHandler.cs
- JournalEntryStack.cs
- WpfKnownMemberInvoker.cs
- Assembly.cs
- WindowsScroll.cs
- ProfileGroupSettingsCollection.cs
- CellQuery.cs
- DataGridViewTextBoxEditingControl.cs
- ByteStack.cs
- SerializerWriterEventHandlers.cs
- ObjectMaterializedEventArgs.cs
- DrawToolTipEventArgs.cs
- OneToOneMappingSerializer.cs
- EnterpriseServicesHelper.cs
- FlowDocumentScrollViewerAutomationPeer.cs
- RealizationContext.cs
- UrlPropertyAttribute.cs
- ColorAnimationBase.cs
- DataServiceRequestException.cs
- ThreadStateException.cs
- MulticastOption.cs
- Int32Collection.cs
- SymDocumentType.cs
- Knowncolors.cs
- HttpCachePolicyBase.cs
- DesignerTransaction.cs
- StylusTip.cs
- FormViewRow.cs
- QueryCursorEventArgs.cs
- WhitespaceSignificantCollectionAttribute.cs
- WorkflowApplication.cs
- ExtenderControl.cs
- DesignerWidgets.cs
- PeerApplication.cs
- basevalidator.cs
- DataSourceBooleanViewSchemaConverter.cs
- DataAccessor.cs
- CodeLabeledStatement.cs
- ThrowHelper.cs
- ExceptionValidationRule.cs
- StringCollection.cs
- Profiler.cs
- StylusButtonCollection.cs
- ExclusiveCanonicalizationTransform.cs
- Vector3DCollectionValueSerializer.cs
- MimeFormatter.cs
- XmlTextReader.cs
- HttpModuleActionCollection.cs
- IDQuery.cs
- UnhandledExceptionEventArgs.cs
- CodeComment.cs
- StylusPointPropertyUnit.cs
- HwndSourceKeyboardInputSite.cs
- Geometry3D.cs
- DataGridViewComboBoxColumn.cs
- DynamicAttribute.cs