Code:
/ 4.0 / 4.0 / DEVDIV_TFS / Dev10 / Releases / RTMRel / ndp / clr / src / ManagedLibraries / Remoting / Channels / IPC / PortCache.cs / 1305376 / PortCache.cs
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//============================================================================
// File: PortCache.cs
// Author: [....]@Microsoft.Com
// Summary: Implements a cache for port handles
//
//=========================================================================
using System;
using System.Collections;
using System.Threading;
using System.Security.Principal;
namespace System.Runtime.Remoting.Channels.Ipc
{
internal class PortConnection
{
private IpcPort _port;
private DateTime _socketLastUsed;
internal PortConnection(IpcPort port)
{
_port = port;
_socketLastUsed = DateTime.Now;
}
internal IpcPort Port { get { return _port; } }
internal DateTime LastUsed { get { return _socketLastUsed; } }
}
internal class ConnectionCache
{
// collection of RemoteConnection's.
private static Hashtable _connections = new Hashtable();
// socket timeout data
private static RegisteredWaitHandle _registeredWaitHandle;
private static WaitOrTimerCallback _socketTimeoutDelegate;
private static AutoResetEvent _socketTimeoutWaitHandle;
private static TimeSpan _socketTimeoutPollTime = TimeSpan.FromSeconds(10);
private static TimeSpan _portLifetime = TimeSpan.FromSeconds(10);
static ConnectionCache()
{
InitializeConnectionTimeoutHandler();
}
private static void InitializeConnectionTimeoutHandler()
{
_socketTimeoutDelegate = new WaitOrTimerCallback(TimeoutConnections);
_socketTimeoutWaitHandle = new AutoResetEvent(false);
_registeredWaitHandle =
ThreadPool.UnsafeRegisterWaitForSingleObject(
_socketTimeoutWaitHandle,
_socketTimeoutDelegate,
"IpcConnectionTimeout",
_socketTimeoutPollTime,
true); // execute only once
} // InitializeSocketTimeoutHandler
private static void TimeoutConnections(Object state, Boolean wasSignalled)
{
DateTime currentTime = DateTime.UtcNow;
lock (_connections)
{
foreach (DictionaryEntry entry in _connections)
{
PortConnection connection = (PortConnection)entry.Value;
if (DateTime.Now - connection.LastUsed > _portLifetime)
connection.Port.Dispose();
}
}
_registeredWaitHandle.Unregister(null);
_registeredWaitHandle =
ThreadPool.UnsafeRegisterWaitForSingleObject(
_socketTimeoutWaitHandle,
_socketTimeoutDelegate,
"IpcConnectionTimeout",
_socketTimeoutPollTime,
true); // execute only once
} // TimeoutConnections
// The key is expected to of the form portName
public IpcPort GetConnection(String portName, bool secure, TokenImpersonationLevel level, int timeout)
{
PortConnection connection = null;
lock (_connections)
{
bool cacheable = true;
if (secure)
{
try
{
WindowsIdentity currentId = WindowsIdentity.GetCurrent(true/*ifImpersonating*/);
if (currentId != null)
{
cacheable = false;
currentId.Dispose();
}
}
catch(Exception)
{
cacheable = false;
}
}
if (cacheable)
{
connection = (PortConnection)_connections[portName];
}
if (connection == null || connection.Port.IsDisposed)
{
connection = new PortConnection(IpcPort.Connect(portName, secure, level, timeout));
connection.Port.Cacheable = cacheable;
}
else
{
// Remove the connection from the cache
_connections.Remove(portName);
}
}
return connection.Port;
} // GetSocket
public void ReleaseConnection(IpcPort port)
{
string portName = port.Name;
PortConnection connection = (PortConnection)_connections[portName];
if (port.Cacheable && (connection == null || connection.Port.IsDisposed))
{
lock(_connections)
{
_connections[portName] = new PortConnection(port);
}
}
else
{
// there should have been a connection, so let's just close
// this socket.
port.Dispose();
}
} // ReleasePort
} // ConnectionCache
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//============================================================================
// File: PortCache.cs
// Author: [....]@Microsoft.Com
// Summary: Implements a cache for port handles
//
//=========================================================================
using System;
using System.Collections;
using System.Threading;
using System.Security.Principal;
namespace System.Runtime.Remoting.Channels.Ipc
{
internal class PortConnection
{
private IpcPort _port;
private DateTime _socketLastUsed;
internal PortConnection(IpcPort port)
{
_port = port;
_socketLastUsed = DateTime.Now;
}
internal IpcPort Port { get { return _port; } }
internal DateTime LastUsed { get { return _socketLastUsed; } }
}
internal class ConnectionCache
{
// collection of RemoteConnection's.
private static Hashtable _connections = new Hashtable();
// socket timeout data
private static RegisteredWaitHandle _registeredWaitHandle;
private static WaitOrTimerCallback _socketTimeoutDelegate;
private static AutoResetEvent _socketTimeoutWaitHandle;
private static TimeSpan _socketTimeoutPollTime = TimeSpan.FromSeconds(10);
private static TimeSpan _portLifetime = TimeSpan.FromSeconds(10);
static ConnectionCache()
{
InitializeConnectionTimeoutHandler();
}
private static void InitializeConnectionTimeoutHandler()
{
_socketTimeoutDelegate = new WaitOrTimerCallback(TimeoutConnections);
_socketTimeoutWaitHandle = new AutoResetEvent(false);
_registeredWaitHandle =
ThreadPool.UnsafeRegisterWaitForSingleObject(
_socketTimeoutWaitHandle,
_socketTimeoutDelegate,
"IpcConnectionTimeout",
_socketTimeoutPollTime,
true); // execute only once
} // InitializeSocketTimeoutHandler
private static void TimeoutConnections(Object state, Boolean wasSignalled)
{
DateTime currentTime = DateTime.UtcNow;
lock (_connections)
{
foreach (DictionaryEntry entry in _connections)
{
PortConnection connection = (PortConnection)entry.Value;
if (DateTime.Now - connection.LastUsed > _portLifetime)
connection.Port.Dispose();
}
}
_registeredWaitHandle.Unregister(null);
_registeredWaitHandle =
ThreadPool.UnsafeRegisterWaitForSingleObject(
_socketTimeoutWaitHandle,
_socketTimeoutDelegate,
"IpcConnectionTimeout",
_socketTimeoutPollTime,
true); // execute only once
} // TimeoutConnections
// The key is expected to of the form portName
public IpcPort GetConnection(String portName, bool secure, TokenImpersonationLevel level, int timeout)
{
PortConnection connection = null;
lock (_connections)
{
bool cacheable = true;
if (secure)
{
try
{
WindowsIdentity currentId = WindowsIdentity.GetCurrent(true/*ifImpersonating*/);
if (currentId != null)
{
cacheable = false;
currentId.Dispose();
}
}
catch(Exception)
{
cacheable = false;
}
}
if (cacheable)
{
connection = (PortConnection)_connections[portName];
}
if (connection == null || connection.Port.IsDisposed)
{
connection = new PortConnection(IpcPort.Connect(portName, secure, level, timeout));
connection.Port.Cacheable = cacheable;
}
else
{
// Remove the connection from the cache
_connections.Remove(portName);
}
}
return connection.Port;
} // GetSocket
public void ReleaseConnection(IpcPort port)
{
string portName = port.Name;
PortConnection connection = (PortConnection)_connections[portName];
if (port.Cacheable && (connection == null || connection.Port.IsDisposed))
{
lock(_connections)
{
_connections[portName] = new PortConnection(port);
}
}
else
{
// there should have been a connection, so let's just close
// this socket.
port.Dispose();
}
} // ReleasePort
} // ConnectionCache
}
// 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
- TextUtf8RawTextWriter.cs
- ButtonBaseAdapter.cs
- ResolveRequestResponseAsyncResult.cs
- HotSpot.cs
- ObjectDataSourceStatusEventArgs.cs
- Model3DGroup.cs
- StringReader.cs
- XPathQilFactory.cs
- DateTimeOffsetStorage.cs
- CanExecuteRoutedEventArgs.cs
- UInt32Converter.cs
- MultiByteCodec.cs
- TextViewSelectionProcessor.cs
- TextSpan.cs
- ImageBrush.cs
- DoubleCollectionConverter.cs
- _NegotiateClient.cs
- Script.cs
- TextEditorCharacters.cs
- FuncTypeConverter.cs
- AccessDataSourceView.cs
- PropertyGridView.cs
- ObjectDataSourceSelectingEventArgs.cs
- TreeNodeClickEventArgs.cs
- SetUserPreferenceRequest.cs
- NotConverter.cs
- HandleValueEditor.cs
- IERequestCache.cs
- SQLByte.cs
- CircleHotSpot.cs
- DetailsViewDeletedEventArgs.cs
- FormatStringEditor.cs
- WSSecurityJan2004.cs
- HighContrastHelper.cs
- Vector3D.cs
- CodeExpressionStatement.cs
- EntryWrittenEventArgs.cs
- ImmComposition.cs
- TemplatePropertyEntry.cs
- SoapMessage.cs
- SqlStatistics.cs
- ItemsChangedEventArgs.cs
- GeneratedView.cs
- AssemblyAssociatedContentFileAttribute.cs
- DiagnosticsElement.cs
- CodeDelegateCreateExpression.cs
- PromptEventArgs.cs
- _NestedSingleAsyncResult.cs
- CacheDependency.cs
- PrinterUnitConvert.cs
- Emitter.cs
- QilNode.cs
- CheckedPointers.cs
- XmlLanguage.cs
- PropertyMap.cs
- DrawingCollection.cs
- UnsafeNativeMethods.cs
- SqlUserDefinedAggregateAttribute.cs
- SqlConnectionHelper.cs
- ContentElement.cs
- DbCommandTree.cs
- ToolboxItemFilterAttribute.cs
- AspNetSynchronizationContext.cs
- SecurityUtils.cs
- RuntimeCompatibilityAttribute.cs
- DataListItemEventArgs.cs
- RadioButtonList.cs
- WebPartConnectionsDisconnectVerb.cs
- ProviderConnectionPoint.cs
- IndexerReference.cs
- MatrixTransform.cs
- contentDescriptor.cs
- HiddenFieldPageStatePersister.cs
- TraceEventCache.cs
- WebPartDisplayMode.cs
- ComplexBindingPropertiesAttribute.cs
- WinEventHandler.cs
- SqlWebEventProvider.cs
- PersianCalendar.cs
- MessageBox.cs
- MailAddressCollection.cs
- CopyAttributesAction.cs
- ArrayTypeMismatchException.cs
- WebPartVerbsEventArgs.cs
- InkCanvasInnerCanvas.cs
- VisualStyleInformation.cs
- StandardCommands.cs
- FixedHighlight.cs
- DataGridViewColumnCollectionDialog.cs
- ConfigsHelper.cs
- ControlBuilder.cs
- SmiRequestExecutor.cs
- SettingsAttributeDictionary.cs
- Quad.cs
- TableLayoutPanelCellPosition.cs
- ProtocolsConfigurationHandler.cs
- ShapeTypeface.cs
- DispatcherOperation.cs
- ToolStripScrollButton.cs
- DataRowComparer.cs