private static SuspendState SuspendImpl(ICollection <ISuspendibleRegisteredObject> allRegisteredObjects) { // Our behavior is: // - We'll call each registered object's suspend method serially. // - All methods have a combined 5 seconds to respond, at which // point we'll forcibly return to our caller. // - If a Resume call comes in, we'll not call any Suspend methods // we haven't yet gotten around to, and we'll execute each // resume callback we got. // - Resume callbacks may fire in parallel, even if Suspend methods // fire sequentially. // - Resume methods fire asynchronously, so other events (such as // Stop or a new Suspend call) could happen while a Resume callback // is in progress. CountdownEvent countdownEvent = new CountdownEvent(2); SuspendState suspendState = new SuspendState(allRegisteredObjects); // Unsafe QUWI since occurs outside the context of a request. // We are not concerned about impersonation, identity, etc. // Invoke any registered subscribers to let them know that we're about // to suspend. This is done in parallel with ASP.NET's own cleanup below. if (allRegisteredObjects.Count > 0) { ThreadPool.UnsafeQueueUserWorkItem(_ => { suspendState.Suspend(); countdownEvent.Signal(); }, null); } else { countdownEvent.Signal(); // nobody is subscribed } // Release any unnecessary memory that we're holding on to. The GC will // be able to reclaim these, which means that we'll have to page in less // memory when the next request comes in. ThreadPool.UnsafeQueueUserWorkItem(_ => { // Release any char[] buffers we're keeping around HttpWriter.ReleaseAllPooledBuffers(); // Trim expired entries from the runtime cache var cache = HttpRuntime.GetCacheInternal(createIfDoesNotExist: false); if (cache != null) { cache.TrimCache(0); } // Trim all pooled HttpApplication instances HttpApplicationFactory.TrimApplicationInstances(removeAll: true); countdownEvent.Signal(); }, null); if (Debug.IsDebuggerPresent()) { countdownEvent.Wait(); // to assist with debugging, don't time out if a debugger is attached } else { countdownEvent.Wait(_suspendMethodTimeout); // blocking call, ok for our needs since has finite wait time } return(suspendState); }