GetOrCreateQueue() static private méthode

Queue factory. Always synchronized.

static private GetOrCreateQueue ( int durationMilliseconds ) : Queue
durationMilliseconds int
Résultat System.Collections.Queue
Exemple #1
0
        internal void Close()
        {
            site.Close();

            // Can't call AppDomain.Unload() from a user thread.
            TimerThread.GetOrCreateQueue(0).CreateTimer(new TimerThread.Callback(CloseAppDomainCallback), appDomainIndex);
            GC.SuppressFinalize(this);
        }
Exemple #2
0
 internal ConnectionPool(System.Net.ServicePoint servicePoint, int maxPoolSize, int minPoolSize, int idleTimeout, CreateConnectionDelegate createConnectionCallback)
 {
     this.m_CreateConnectionCallback = createConnectionCallback;
     this.m_MaxPoolSize  = maxPoolSize;
     this.m_MinPoolSize  = minPoolSize;
     this.m_ServicePoint = servicePoint;
     this.Initialize();
     if (idleTimeout > 0)
     {
         this.m_CleanupQueue = TimerThread.GetOrCreateQueue((idleTimeout == 1) ? 1 : (idleTimeout / 2));
         this.m_CleanupQueue.CreateTimer(s_CleanupCallback, this);
     }
 }
        /// <summary>
        ///    <para>Constructor - binds pool with a servicePoint and sets up a cleanup Timer to nuke Idle Connections</para>
        /// </summary>
        internal ConnectionPool(ServicePoint servicePoint, int maxPoolSize, int minPoolSize, int idleTimeout, CreateConnectionDelegate createConnectionCallback) : base()
        {
            m_State = State.Initializing;

            m_CreateConnectionCallback = createConnectionCallback;
            m_MaxPoolSize  = maxPoolSize;
            m_MinPoolSize  = minPoolSize;
            m_ServicePoint = servicePoint;

            Initialize();

            if (idleTimeout > 0)
            {
                m_CleanupQueue = TimerThread.GetOrCreateQueue(idleTimeout / 2);
                m_CleanupQueue.CreateTimer(s_CleanupCallback, this);
            }
        }
        /// <summary>
        ///    <para>Constructor - binds pool with a servicePoint and sets up a cleanup Timer to remove Idle Connections</para>
        /// </summary>
        internal ConnectionPool(ServicePoint servicePoint, int maxPoolSize, int minPoolSize, int idleTimeout, CreateConnectionDelegate createConnectionCallback) : base()
        {
            m_State = State.Initializing;

            m_CreateConnectionCallback = createConnectionCallback;
            m_MaxPoolSize  = maxPoolSize;
            m_MinPoolSize  = minPoolSize;
            m_ServicePoint = servicePoint;

            Initialize();

            if (idleTimeout > 0)
            {
                // special case: if the timeout value is 1 then the timer thread should have a duration
                // of 1 to avoid having the timer callback run constantly
                m_CleanupQueue = TimerThread.GetOrCreateQueue(idleTimeout == 1 ? 1 : (idleTimeout / 2));
                m_CleanupQueue.CreateTimer(s_CleanupCallback, this);
            }
        }
Exemple #5
0
        private void CreateAppDomain()
        {
            // Locking s_AppDomains must happen in a CER so we don't orphan a lock that gets taken by AppDomain.DomainUnload.
            bool lockHeld = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                Monitor.Enter(s_AppDomains.SyncRoot, ref lockHeld);

                if (s_CleanedUp)
                {
                    throw new InvalidOperationException(SR.GetString(SR.net_cant_perform_during_shutdown));
                }

                // Create singleton.
                if (s_AppDomainInfo == null)
                {
                    s_AppDomainInfo = new AppDomainSetup();
                    s_AppDomainInfo.DisallowBindingRedirects = true;
                    s_AppDomainInfo.DisallowCodeDownload     = true;

                    NamedPermissionSet perms = new NamedPermissionSet("__WebProxySandbox", PermissionState.None);
                    perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                    ApplicationTrust trust = new ApplicationTrust();
                    trust.DefaultGrantSet            = new PolicyStatement(perms);
                    s_AppDomainInfo.ApplicationTrust = trust;
                    s_AppDomainInfo.ApplicationBase  = Environment.SystemDirectory;
                }

                // If something's already in s_ExcessAppDomain, try to dislodge it again.
                AppDomain excessAppDomain = s_ExcessAppDomain;
                if (excessAppDomain != null)
                {
                    TimerThread.GetOrCreateQueue(0).CreateTimer(new TimerThread.Callback(CloseAppDomainCallback), excessAppDomain);
                    throw new InvalidOperationException(SR.GetString(SR.net_cant_create_environment));
                }

                appDomainIndex = s_NextAppDomainIndex++;
                try { }
                finally
                {
                    PermissionSet permissionSet = new PermissionSet(PermissionState.None);
                    permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

                    //

                    s_ExcessAppDomain = AppDomain.CreateDomain(c_appDomainName, null, s_AppDomainInfo, permissionSet, null);

                    try
                    {
                        s_AppDomains.Add(appDomainIndex, s_ExcessAppDomain);

                        // This indicates to the finally and the finalizer that everything succeeded.
                        scriptDomain = s_ExcessAppDomain;
                    }
                    finally
                    {
                        // ReferenceEquals has a ReliabilityContract.
                        if (object.ReferenceEquals(scriptDomain, s_ExcessAppDomain))
                        {
                            s_ExcessAppDomain = null;
                        }
                        else
                        {
                            // Something failed.  Leave the domain in s_ExcessAppDomain until we can get rid of it.  No
                            // more AppDomains can be created until we do.  In the mean time, keep attempting to get the
                            // TimerThread to remove it.  Also, might as well remove it from the hash if it made it in.
                            try
                            {
                                s_AppDomains.Remove(appDomainIndex);
                            }
                            finally
                            {
                                // Can't call AppDomain.Unload from a user thread (or in a lock).
                                TimerThread.GetOrCreateQueue(0).CreateTimer(new TimerThread.Callback(CloseAppDomainCallback), s_ExcessAppDomain);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (lockHeld)
                {
                    Monitor.Exit(s_AppDomains.SyncRoot);
                }
            }
        }
        // Downloads and compiles the script from a given Uri.
        // This code can be called by config for a downloaded control, we need to assert.
        // This code is called holding the lock.
        private AutoWebProxyState DownloadAndCompile(Uri location)
        {
            GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() location:" + ValidationHelper.ToString(location));
            AutoWebProxyState newState = AutoWebProxyState.DownloadFailure;
            WebResponse       response = null;

            TimerThread.Timer         timer             = null;
            AutoWebProxyScriptWrapper newScriptInstance = null;

            // Can't assert this in declarative form (DCR?). This Assert() is needed to be able to create the request to download the proxy script.
            ExceptionHelper.WebPermissionUnrestricted.Assert();
            try
            {
                lock (lockObject)
                {
                    if (aborted)
                    {
                        throw new WebException(NetRes.GetWebStatusString("net_requestaborted",
                                                                         WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
                    }

                    request = WebRequest.Create(location);
                }

                request.Timeout             = Timeout.Infinite;
                request.CachePolicy         = new RequestCachePolicy(RequestCacheLevel.Default);
                request.ConnectionGroupName = "__WebProxyScript";

                // We have an opportunity here, if caching is disabled AppDomain-wide, to override it with a
                // custom, trivial cache-provider to get a similar semantic.
                //
                // We also want to have a backup caching key in the case when IE has locked an expired script response
                //
                if (request.CacheProtocol != null)
                {
                    GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Using backup caching.");
                    request.CacheProtocol = new RequestCacheProtocol(backupCache, request.CacheProtocol.Validator);
                }

                HttpWebRequest httpWebRequest = request as HttpWebRequest;
                if (httpWebRequest != null)
                {
                    httpWebRequest.Accept    = "*/*";
                    httpWebRequest.UserAgent = this.GetType().FullName + "/" + Environment.Version;
                    httpWebRequest.KeepAlive = false;
                    httpWebRequest.Pipelined = false;
                    httpWebRequest.InternalConnectionGroup = true;
                }
                else
                {
                    FtpWebRequest ftpWebRequest = request as FtpWebRequest;
                    if (ftpWebRequest != null)
                    {
                        ftpWebRequest.KeepAlive = false;
                    }
                }

                // Use no proxy, default cache - initiate the download.
                request.Proxy       = null;
                request.Credentials = Engine.Credentials;

                // Use our own timeout timer so that it can encompass the whole request, not just the headers.
                if (timerQueue == null)
                {
                    timerQueue = TimerThread.GetOrCreateQueue(SettingsSectionInternal.Section.DownloadTimeout);
                }
                timer    = timerQueue.CreateTimer(timerCallback, request);
                response = request.GetResponse();

                // Check Last Modified.
                DateTime        lastModified = DateTime.MinValue;
                HttpWebResponse httpResponse = response as HttpWebResponse;
                if (httpResponse != null)
                {
                    lastModified = httpResponse.LastModified;
                }
                else
                {
                    FtpWebResponse ftpResponse = response as FtpWebResponse;
                    if (ftpResponse != null)
                    {
                        lastModified = ftpResponse.LastModified;
                    }
                }
                GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() lastModified:" + lastModified.ToString() + " (script):" + (scriptInstance == null ? "(null)" : scriptInstance.LastModified.ToString()));
                if (scriptInstance != null && lastModified != DateTime.MinValue && scriptInstance.LastModified == lastModified)
                {
                    newScriptInstance = scriptInstance;
                    newState          = AutoWebProxyState.Completed;
                }
                else
                {
                    string scriptBody   = null;
                    byte[] scriptBuffer = null;
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        SingleItemRequestCache.ReadOnlyStream ros = responseStream as SingleItemRequestCache.ReadOnlyStream;
                        if (ros != null)
                        {
                            scriptBuffer = ros.Buffer;
                        }
                        if (scriptInstance != null && scriptBuffer != null && scriptBuffer == scriptInstance.Buffer)
                        {
                            scriptInstance.LastModified = lastModified;
                            newScriptInstance           = scriptInstance;
                            newState = AutoWebProxyState.Completed;
                            GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Buffer matched - reusing Engine.");
                        }
                        else
                        {
                            using (StreamReader streamReader = new StreamReader(responseStream))
                            {
                                scriptBody = streamReader.ReadToEnd();
                            }
                        }
                    }

                    WebResponse tempResponse = response;
                    response = null;
                    tempResponse.Close();
                    timer.Cancel();
                    timer = null;

                    if (newState != AutoWebProxyState.Completed)
                    {
                        GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() IsFromCache:" + tempResponse.IsFromCache.ToString() + " scriptInstance:" + ValidationHelper.HashString(scriptInstance));
                        if (scriptInstance != null && scriptBody == scriptInstance.ScriptBody)
                        {
                            GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Script matched - using existing Engine.");
                            scriptInstance.LastModified = lastModified;
                            if (scriptBuffer != null)
                            {
                                scriptInstance.Buffer = scriptBuffer;
                            }
                            newScriptInstance = scriptInstance;
                            newState          = AutoWebProxyState.Completed;
                        }
                        else
                        {
                            GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Creating AutoWebProxyScriptWrapper.");
                            newScriptInstance = new AutoWebProxyScriptWrapper();
                            newScriptInstance.LastModified = lastModified;

                            if (newScriptInstance.Compile(location, scriptBody, scriptBuffer))
                            {
                                newState = AutoWebProxyState.Completed;
                            }
                            else
                            {
                                newState = AutoWebProxyState.CompilationFailure;
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (Logging.On)
                {
                    Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_script_download_compile_error, exception));
                }
                GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Download() threw:" + ValidationHelper.ToString(exception));
            }
            finally
            {
                if (timer != null)
                {
                    timer.Cancel();
                }

                //
                try
                {
                    if (response != null)
                    {
                        response.Close();
                    }
                }
                finally
                {
                    WebPermission.RevertAssert();

                    // The request is not needed anymore. Set it to null, so if Abort() gets called,
                    // after this point, it will result in a no-op.
                    request = null;
                }
            }

            if ((newState == AutoWebProxyState.Completed) && (scriptInstance != newScriptInstance))
            {
                if (scriptInstance != null)
                {
                    scriptInstance.Close();
                }

                scriptInstance = newScriptInstance;
            }

            GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() retuning newState:" + ValidationHelper.ToString(newState));
            return(newState);
        }
 internal void Close()
 {
     this.site.Close();
     TimerThread.GetOrCreateQueue(0).CreateTimer(new TimerThread.Callback(AutoWebProxyScriptWrapper.CloseAppDomainCallback), this.appDomainIndex);
     GC.SuppressFinalize(this);
 }
        private void CreateAppDomain()
        {
            bool lockTaken = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                Monitor.Enter(s_AppDomains.SyncRoot, ref lockTaken);
                if (s_CleanedUp)
                {
                    throw new InvalidOperationException(SR.GetString("net_cant_perform_during_shutdown"));
                }
                if (s_AppDomainInfo == null)
                {
                    s_AppDomainInfo = new AppDomainSetup();
                    s_AppDomainInfo.DisallowBindingRedirects = true;
                    s_AppDomainInfo.DisallowCodeDownload     = true;
                    NamedPermissionSet permSet = new NamedPermissionSet("__WebProxySandbox", PermissionState.None);
                    permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                    ApplicationTrust trust = new ApplicationTrust {
                        DefaultGrantSet = new PolicyStatement(permSet)
                    };
                    s_AppDomainInfo.ApplicationTrust = trust;
                    s_AppDomainInfo.ApplicationBase  = Environment.SystemDirectory;
                }
                AppDomain context = s_ExcessAppDomain;
                if (context != null)
                {
                    TimerThread.GetOrCreateQueue(0).CreateTimer(new TimerThread.Callback(AutoWebProxyScriptWrapper.CloseAppDomainCallback), context);
                    throw new InvalidOperationException(SR.GetString("net_cant_create_environment"));
                }
                this.appDomainIndex = s_NextAppDomainIndex++;
                try
                {
                }
                finally
                {
                    PermissionSet grantSet = new PermissionSet(PermissionState.None);
                    grantSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                    s_ExcessAppDomain = AppDomain.CreateDomain("WebProxyScript", null, s_AppDomainInfo, grantSet, null);
                    try
                    {
                        s_AppDomains.Add(this.appDomainIndex, s_ExcessAppDomain);
                        this.scriptDomain = s_ExcessAppDomain;
                    }
                    finally
                    {
                        if (object.ReferenceEquals(this.scriptDomain, s_ExcessAppDomain))
                        {
                            s_ExcessAppDomain = null;
                        }
                        else
                        {
                            try
                            {
                                s_AppDomains.Remove(this.appDomainIndex);
                            }
                            finally
                            {
                                TimerThread.GetOrCreateQueue(0).CreateTimer(new TimerThread.Callback(AutoWebProxyScriptWrapper.CloseAppDomainCallback), s_ExcessAppDomain);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (lockTaken)
                {
                    Monitor.Exit(s_AppDomains.SyncRoot);
                }
            }
        }
Exemple #9
0
        private BaseWebProxyFinder.AutoWebProxyState DownloadAndCompile(Uri location)
        {
            BaseWebProxyFinder.AutoWebProxyState downloadFailure = BaseWebProxyFinder.AutoWebProxyState.DownloadFailure;
            WebResponse response = null;

            TimerThread.Timer         timer          = null;
            AutoWebProxyScriptWrapper scriptInstance = null;

            ExceptionHelper.WebPermissionUnrestricted.Assert();
            try
            {
                lock (this.lockObject)
                {
                    if (this.aborted)
                    {
                        throw new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
                    }
                    this.request = WebRequest.Create(location);
                }
                this.request.Timeout             = -1;
                this.request.CachePolicy         = new RequestCachePolicy(RequestCacheLevel.Default);
                this.request.ConnectionGroupName = "__WebProxyScript";
                if (this.request.CacheProtocol != null)
                {
                    this.request.CacheProtocol = new RequestCacheProtocol(this.backupCache, this.request.CacheProtocol.Validator);
                }
                HttpWebRequest request = this.request as HttpWebRequest;
                if (request != null)
                {
                    request.Accept    = "*/*";
                    request.UserAgent = base.GetType().FullName + "/" + Environment.Version;
                    request.KeepAlive = false;
                    request.Pipelined = false;
                    request.InternalConnectionGroup = true;
                }
                else
                {
                    FtpWebRequest request2 = this.request as FtpWebRequest;
                    if (request2 != null)
                    {
                        request2.KeepAlive = false;
                    }
                }
                this.request.Proxy       = null;
                this.request.Credentials = base.Engine.Credentials;
                if (timerQueue == null)
                {
                    timerQueue = TimerThread.GetOrCreateQueue(SettingsSectionInternal.Section.DownloadTimeout);
                }
                timer    = timerQueue.CreateTimer(timerCallback, this.request);
                response = this.request.GetResponse();
                DateTime        minValue  = DateTime.MinValue;
                HttpWebResponse response2 = response as HttpWebResponse;
                if (response2 != null)
                {
                    minValue = response2.LastModified;
                }
                else
                {
                    FtpWebResponse response3 = response as FtpWebResponse;
                    if (response3 != null)
                    {
                        minValue = response3.LastModified;
                    }
                }
                if (((this.scriptInstance != null) && (minValue != DateTime.MinValue)) && (this.scriptInstance.LastModified == minValue))
                {
                    scriptInstance  = this.scriptInstance;
                    downloadFailure = BaseWebProxyFinder.AutoWebProxyState.Completed;
                }
                else
                {
                    string scriptBody = null;
                    byte[] buffer     = null;
                    using (Stream stream = response.GetResponseStream())
                    {
                        SingleItemRequestCache.ReadOnlyStream stream2 = stream as SingleItemRequestCache.ReadOnlyStream;
                        if (stream2 != null)
                        {
                            buffer = stream2.Buffer;
                        }
                        if (((this.scriptInstance != null) && (buffer != null)) && (buffer == this.scriptInstance.Buffer))
                        {
                            this.scriptInstance.LastModified = minValue;
                            scriptInstance  = this.scriptInstance;
                            downloadFailure = BaseWebProxyFinder.AutoWebProxyState.Completed;
                        }
                        else
                        {
                            using (StreamReader reader = new StreamReader(stream))
                            {
                                scriptBody = reader.ReadToEnd();
                            }
                        }
                    }
                    WebResponse response4 = response;
                    response = null;
                    response4.Close();
                    timer.Cancel();
                    timer = null;
                    if (downloadFailure != BaseWebProxyFinder.AutoWebProxyState.Completed)
                    {
                        if ((this.scriptInstance != null) && (scriptBody == this.scriptInstance.ScriptBody))
                        {
                            this.scriptInstance.LastModified = minValue;
                            if (buffer != null)
                            {
                                this.scriptInstance.Buffer = buffer;
                            }
                            scriptInstance  = this.scriptInstance;
                            downloadFailure = BaseWebProxyFinder.AutoWebProxyState.Completed;
                        }
                        else
                        {
                            scriptInstance = new AutoWebProxyScriptWrapper {
                                LastModified = minValue
                            };
                            if (scriptInstance.Compile(location, scriptBody, buffer))
                            {
                                downloadFailure = BaseWebProxyFinder.AutoWebProxyState.Completed;
                            }
                            else
                            {
                                downloadFailure = BaseWebProxyFinder.AutoWebProxyState.CompilationFailure;
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (Logging.On)
                {
                    Logging.PrintWarning(Logging.Web, SR.GetString("net_log_proxy_script_download_compile_error", new object[] { exception }));
                }
            }
            finally
            {
                if (timer != null)
                {
                    timer.Cancel();
                }
                try
                {
                    if (response != null)
                    {
                        response.Close();
                    }
                }
                finally
                {
                    CodeAccessPermission.RevertAssert();
                    this.request = null;
                }
            }
            if ((downloadFailure == BaseWebProxyFinder.AutoWebProxyState.Completed) && (this.scriptInstance != scriptInstance))
            {
                if (this.scriptInstance != null)
                {
                    this.scriptInstance.Close();
                }
                this.scriptInstance = scriptInstance;
            }
            return(downloadFailure);
        }