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
- ChildrenQuery.cs
- sqlnorm.cs
- ConversionContext.cs
- CategoryNameCollection.cs
- Color.cs
- ObjectKeyFrameCollection.cs
- EditorZone.cs
- GenericIdentity.cs
- FileLevelControlBuilderAttribute.cs
- RankException.cs
- DrawItemEvent.cs
- BamlLocalizabilityResolver.cs
- FontStretches.cs
- IdentityValidationException.cs
- BaseTemplateParser.cs
- oledbmetadatacollectionnames.cs
- ExpressionEditorAttribute.cs
- FormattedTextSymbols.cs
- RegionData.cs
- UniqueTransportManagerRegistration.cs
- InvalidFilterCriteriaException.cs
- Parser.cs
- DbModificationCommandTree.cs
- BigInt.cs
- ClosableStream.cs
- InputLanguage.cs
- MessagingActivityHelper.cs
- ImageField.cs
- ASCIIEncoding.cs
- ServiceMetadataPublishingElement.cs
- XmlHierarchicalEnumerable.cs
- ListViewUpdateEventArgs.cs
- HttpCacheParams.cs
- String.cs
- NativeMethods.cs
- GiveFeedbackEventArgs.cs
- FactoryGenerator.cs
- SHA1CryptoServiceProvider.cs
- SHA1.cs
- LoginView.cs
- PropertyExpression.cs
- Image.cs
- Currency.cs
- ElementHostAutomationPeer.cs
- Control.cs
- CompilerGeneratedAttribute.cs
- EditCommandColumn.cs
- UnionExpr.cs
- SizeF.cs
- ToolStripItemCollection.cs
- WebPartEditorApplyVerb.cs
- ProfileModule.cs
- DataRelationCollection.cs
- HttpCookie.cs
- RegistrationServices.cs
- Pool.cs
- DataBoundControlParameterTarget.cs
- unsafenativemethodsother.cs
- User.cs
- SuppressMessageAttribute.cs
- BinaryObjectReader.cs
- HttpModuleActionCollection.cs
- UIElementParaClient.cs
- ConstraintStruct.cs
- ResourceDescriptionAttribute.cs
- FontConverter.cs
- GrammarBuilderRuleRef.cs
- WebEventTraceProvider.cs
- WebPartMenu.cs
- NoPersistScope.cs
- ActivityBuilder.cs
- MouseWheelEventArgs.cs
- DispatcherSynchronizationContext.cs
- NamespaceList.cs
- XhtmlTextWriter.cs
- PropagatorResult.cs
- HelpProvider.cs
- Int16Storage.cs
- SafeSystemMetrics.cs
- CacheEntry.cs
- IxmlLineInfo.cs
- MatrixAnimationBase.cs
- DynamicControlParameter.cs
- SR.cs
- IgnoreDeviceFilterElementCollection.cs
- TimeSpanFormat.cs
- MembershipPasswordException.cs
- X509Certificate2Collection.cs
- ObjectViewListener.cs
- TemplateBindingExtensionConverter.cs
- EntityDataSourceDesigner.cs
- CodeSnippetExpression.cs
- FirewallWrapper.cs
- ToolBarButton.cs
- TrackingServices.cs
- MenuItemStyleCollection.cs
- SecurityContextTokenValidationException.cs
- HttpRawResponse.cs
- BitSet.cs
- WorkflowPageSetupDialog.cs