/// <summary> /// 检查对象是否还没有被释放 /// </summary> /// <exception cref="ObjectDisposedException">如果对象已经释放则触发该异常</exception> protected virtual void CheckNotDisposed() { if (IsDisposed) { var ex = new ObjectDisposedException(GetType().Name); throw ex; } }
protected void Act() { try { _subsystemSession.Connect(); } catch (ObjectDisposedException ex) { _actualException = ex; } }
protected void Act() { try { _subsystemSession.SendData(new byte[0]); } catch (ObjectDisposedException ex) { _actualException = ex; } }
protected void Act() { try { _forwardedPort.Start(); Assert.Fail(); } catch (ObjectDisposedException ex) { _actualException = ex; } }
protected void Act() { try { _sftpFileStream.SetLength(5); Assert.Fail(); } catch (ObjectDisposedException ex) { _actualException = ex; } }
public override bool GetCounterValue(int counterId, bool isNumerator, out long counterValue) { int num; counterValue = -1L; if (this._Disposed) { ObjectDisposedException exception = new ObjectDisposedException("PSCounterSetInstance"); this._tracer.TraceException(exception); return false; } if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out num)) { CounterData data = this._CounterSetInstance.Counters[num]; if (data != null) { counterValue = data.Value; return true; } InvalidOperationException exception2 = new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Lookup for counter corresponding to counter id {0} failed", new object[] { counterId })); this._tracer.TraceException(exception2); } return false; }
private void cleanupWaitQueue () { lock (_waitQueueSync) { if (_waitQueue.Count == 0) return; var ex = new ObjectDisposedException (GetType ().ToString ()); foreach (var ares in _waitQueue) ares.Complete (ex); _waitQueue.Clear (); } }
private void HandleDisposed(ObjectDisposedException e) { Logger.WriteLine("Socket has been closed (ObjectDisposedException: {0})!", TraceEventType.Warning, e); if (this.isConnected) { this.HandleDisconnect(); } }
protected void Dispose (bool disposing) { if (disposing) { try { if (handle != null) { Close (); handle.Dispose (); handle = null; } } finally { var disposedExc = new ObjectDisposedException (GetType ().Name); Interlocked.CompareExchange (ref lastError, disposedExc, null); } } }
private async Task ProcessSentTasksAsync(NetworkStream netStream, SocketPayloadSendTask sendTask) { if (sendTask == null) return; using (sendTask) { var failed = false; var sw = Stopwatch.StartNew(); try { sw.Restart(); StatisticsTracker.IncrementGauge(StatisticGauge.ActiveWriteOperation); if (OnWriteToSocketAttempt != null) OnWriteToSocketAttempt(sendTask.Payload); _log.DebugFormat("Sending data for CorrelationId:{0} Connection:{1}", sendTask.Payload.CorrelationId, Endpoint); await netStream.WriteAsync(sendTask.Payload.Buffer, 0, sendTask.Payload.Buffer.Length).ConfigureAwait(false); _log.DebugFormat("Data sent to CorrelationId:{0} Connection:{1}", sendTask.Payload.CorrelationId, Endpoint); sendTask.Tcp.TrySetResult(sendTask.Payload); } catch (Exception ex) { failed = true; if (_disposeToken.IsCancellationRequested) { var exception = new ObjectDisposedException("Object is disposing."); sendTask.Tcp.TrySetException(exception); throw exception; } sendTask.Tcp.TrySetException(ex); throw; } finally { StatisticsTracker.DecrementGauge(StatisticGauge.ActiveWriteOperation); StatisticsTracker.CompleteNetworkWrite(sendTask.Payload, sw.ElapsedMilliseconds, failed); } } }
bool HandleReadComplete(TransportAsyncCallbackArgs args) { bool completed = true; Exception exception = null; if (args.Exception != null) { exception = args.Exception; } else if (args.BytesTransfered == 0) { exception = new ObjectDisposedException(this.transport.ToString()); } else if (args.BytesTransfered < args.Count) { args.SetBuffer(args.Buffer, args.Offset + args.BytesTransfered, args.Count - args.BytesTransfered); completed = false; } if (completed) { if (exception != null || object.ReferenceEquals(args.CompletedCallback, onFrameComplete)) { ByteBuffer buffer = null; if (exception == null) { buffer = new ByteBuffer(args.Buffer, 0, args.Buffer.Length); this.parent.OnReceiveBuffer(buffer); } else { this.parent.OnIoFault(exception); } } else { // read size completed ok uint size = AmqpBitConverter.ReadUInt(this.sizeBuffer, 0, this.sizeBuffer.Length); if (size > this.maxFrameSize) { completed = true; exception = new AmqpException(AmqpErrorCode.FramingError, CommonResources.GetString(CommonResources.InvalidFrameSize, size, this.maxFrameSize)); this.parent.OnIoFault(exception); } else { byte[] frameBuffer = new byte[size]; Buffer.BlockCopy(this.sizeBuffer, 0, frameBuffer, 0, this.sizeBuffer.Length); args.SetBuffer(frameBuffer, this.sizeBuffer.Length, (int)size - this.sizeBuffer.Length); args.CompletedCallback = onFrameComplete; completed = false; } } } return completed; }
private async Task ProcessReadTaskAsync(NetworkStream netStream, SocketPayloadReadTask readTask) { using (readTask) { try { if (UseStatisticsTracker()) { StatisticsTracker.IncrementGauge(StatisticGauge.ActiveReadOperation); } var readSize = readTask.ReadSize; var result = new List<byte>(readSize); var bytesReceived = 0; while (bytesReceived < readSize) { readSize = readSize - bytesReceived; var buffer = new byte[readSize]; if (OnReadFromSocketAttempt != null) OnReadFromSocketAttempt(readSize); bytesReceived = await netStream.ReadAsync(buffer, 0, readSize, readTask.CancellationToken).ConfigureAwait(false); if (OnBytesReceived != null) OnBytesReceived(bytesReceived); if (bytesReceived <= 0) { using (_client) { _client = null; if (_disposeToken.IsCancellationRequested) { return; } throw new BrokerConnectionException(string.Format("Lost connection to server: {0}", _endpoint), _endpoint); } } result.AddRange(buffer.Take(bytesReceived)); } readTask.Tcp.TrySetResult(result.ToArray()); } catch (Exception ex) { if (_disposeToken.IsCancellationRequested) { var exception = new ObjectDisposedException(string.Format("Object is disposing (KafkaTcpSocket for endpoint: {0})", Endpoint)); readTask.Tcp.TrySetException(exception); throw exception; } if (ex is BrokerConnectionException) { readTask.Tcp.TrySetException(ex); if (_disposeToken.IsCancellationRequested) return; throw; } //if an exception made us lose a connection throw disconnected exception if (_client == null || _client.Connected == false) { var exception = new BrokerConnectionException(string.Format("Lost connection to server: {0}", _endpoint), _endpoint); readTask.Tcp.TrySetException(exception); throw exception; } readTask.Tcp.TrySetException(ex); if (_disposeToken.IsCancellationRequested) return; throw; } finally { if (UseStatisticsTracker()) { StatisticsTracker.DecrementGauge(StatisticGauge.ActiveReadOperation); } } } }
private void DedicatedSocketTask() { while (_disposeToken.IsCancellationRequested == false) { try { //block here until we can get connections then start loop pushing data through network stream var netStream = GetStreamAsync().Result; ProcessNetworkstreamTasks(netStream); } catch (Exception ex) { if (_disposeToken.IsCancellationRequested) { _log.WarnFormat("KafkaTcpSocket thread shutting down because of a dispose call."); var disposeException = new ObjectDisposedException("Object is disposing."); _sendTaskQueue.DrainAndApply(t => t.Tcp.TrySetException(disposeException)); _readTaskQueue.DrainAndApply(t => t.Tcp.TrySetException(disposeException)); return; } if (ex is ServerDisconnectedException) { if (OnServerDisconnected != null) OnServerDisconnected(); _log.ErrorFormat(ex.Message); continue; } _log.ErrorFormat("Exception occured in Socket handler task. Exception: {0}", ex); } } }
void Cleanup(bool close_existing) { lock (registry) { if (close_existing) { // Need to copy this since closing will call UnregisterContext ICollection keys = registry.Keys; var all = new HttpListenerContext[keys.Count]; keys.CopyTo(all, 0); registry.Clear(); for (int i = all.Length - 1; i >= 0; i--) { all[i].Connection.Close(true); } } lock (connections.SyncRoot) { ICollection keys = connections.Keys; var conns = new HttpConnection[keys.Count]; keys.CopyTo(conns, 0); connections.Clear(); for (int i = conns.Length - 1; i >= 0; i--) { conns[i].Close(true); } } lock (ctx_queue) { var ctxs = (HttpListenerContext[])ctx_queue.ToArray(typeof(HttpListenerContext)); ctx_queue.Clear(); for (int i = ctxs.Length - 1; i >= 0; i--) { ctxs[i].Connection.Close(true); } } lock (wait_queue) { Exception exc = new ObjectDisposedException("listener"); foreach (ListenerAsyncResult ares in wait_queue) { ares.Complete(exc); } wait_queue.Clear(); } } }
private void AcceptCallback(object nullState) { bool flag = true; Queue acceptQueue = this.GetAcceptQueue(); while (flag) { LazyAsyncResult lazyAsyncResult = null; SocketError socketError = SocketError.OperationAborted; SocketAddress socketAddress = null; SafeCloseSocket safeCloseSocket = null; Exception ex = null; object result = null; bool flag2 = false; try { Monitor.Enter(this, ref flag2); if (acceptQueue.Count == 0) { break; } lazyAsyncResult = (LazyAsyncResult)acceptQueue.Peek(); if (!this.CleanedUp) { socketAddress = this.m_RightEndPoint.Serialize(); try { safeCloseSocket = SafeCloseSocket.Accept(this.m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size); socketError = (SocketError)(safeCloseSocket.IsInvalid ? Marshal.GetLastWin32Error() : 0); } catch (ObjectDisposedException) { socketError = SocketError.OperationAborted; } catch (Exception ex2) { ex = ex2; } } if (socketError == SocketError.WouldBlock && ex == null) { try { this.m_AsyncEvent.Reset(); if (this.SetAsyncEventSelect(AsyncEventBits.FdAccept)) { break; } } catch (ObjectDisposedException) { } ex = new ObjectDisposedException(base.GetType().FullName); } if (ex != null) { result = ex; } else { if (socketError == SocketError.Success) { result = this.CreateAcceptSocket(safeCloseSocket, this.m_RightEndPoint.Create(socketAddress), true); } else { lazyAsyncResult.ErrorCode = (int)socketError; } } acceptQueue.Dequeue(); if (acceptQueue.Count == 0) { if (!this.CleanedUp) { this.UnsetAsyncEventSelect(); } flag = false; } } finally { if (flag2) { Monitor.Exit(this); } } try { lazyAsyncResult.InvokeCallback(result); } catch { if (flag) { ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(this.AcceptCallback), nullState); } throw; } } }
bool HandleWriteComplete(TransportAsyncCallbackArgs args) { bool done = true; Exception exception = null; if (args.Exception != null) { exception = args.Exception; } else if (args.BytesTransfered == 0) { exception = new ObjectDisposedException(this.transport.ToString()); } else if (args.BytesTransfered < args.Count) { args.SetBuffer(args.Buffer, args.Offset + args.BytesTransfered, args.Count - args.BytesTransfered); done = false; } TransportAsyncCallbackArgs innerArgs = (TransportAsyncCallbackArgs)args.UserToken; if (done && innerArgs.CompletedCallback != null) { innerArgs.Exception = exception; innerArgs.BytesTransfered = innerArgs.Count; innerArgs.CompletedCallback(innerArgs); } return done; }
protected void OnSocketClosedException(ObjectDisposedException e) { if (CaughtClosedSocket != null) CaughtClosedSocket(e); }
bool HandleReadComplete(TransportAsyncCallbackArgs args) { bool completed = true; Exception exception = null; if (args.Exception != null) { exception = args.Exception; } else if (args.BytesTransfered == 0) { exception = new ObjectDisposedException(this.transport.ToString()); } else if (args.BytesTransfered < args.Count) { args.SetBuffer(args.Buffer, args.Offset + args.BytesTransfered, args.Count - args.BytesTransfered); completed = false; } if (completed) { if (exception != null || object.ReferenceEquals(args.CompletedCallback, this.onFrameComplete)) { Action<ByteBuffer, Exception> callback = (Action<ByteBuffer, Exception>)args.UserToken; ByteBuffer buffer = null; if (exception == null) { buffer = ByteBuffer.Wrap(args.Buffer, 0, args.Buffer.Length); } callback(buffer, exception); } else { // read size completed ok uint size = AmqpBitConverter.ReadUInt(this.sizeBuffer, 0, this.sizeBuffer.Length); byte[] frameBuffer = new byte[size]; Buffer.BlockCopy(this.sizeBuffer, 0, frameBuffer, 0, this.sizeBuffer.Length); args.SetBuffer(frameBuffer, this.sizeBuffer.Length, (int)size - this.sizeBuffer.Length); args.CompletedCallback = this.onFrameComplete; completed = false; } } return completed; }
protected void HandleSocketClosed(ObjectDisposedException ex) { if (!_isConnected) return; _isConnected = false; _protocol.ConnectionLost(CloseReason.RemoteClose); }
public void Dispose() { if (inTransaction) RollbackTransaction(); parentHandle?.Dispose(); if (!utxoApplier.Completion.IsCompleted) { // ensure utxo applier has completed, but do not propagate exceptions var ex = new ObjectDisposedException("DeferredChainStateCursor"); ((IDataflowBlock)unspentTxes.WorkQueue).Fault(ex); ((IDataflowBlock)utxoApplier).Fault(ex); try { utxoApplier.Completion.Wait(); } catch (Exception) { } ((IDataflowBlock)unspentTxOutputs.WorkQueue).Fault(ex); ((IDataflowBlock)utxoApplier2).Fault(ex); try { utxoApplier2.Completion.Wait(); } catch (Exception) { } } }
private Exception ConvertObjectDisposedException(ObjectDisposedException originalException, TransferOperation transferOperation) { if (this.timeoutErrorString != null) { return ConvertTimeoutErrorException(originalException, transferOperation, this.timeoutErrorString, this.timeoutErrorTransferOperation); } if (this.aborted) { return new CommunicationObjectAbortedException(System.ServiceModel.SR.GetString("SocketConnectionDisposed"), originalException); } return originalException; }
public override bool GetCounterValue(string counterName, bool isNumerator, out long counterValue) { counterValue = -1L; if (this._Disposed) { ObjectDisposedException exception = new ObjectDisposedException("PSCounterSetInstance"); this._tracer.TraceException(exception); return false; } if (counterName == null) { ArgumentNullException exception2 = new ArgumentNullException("counterName"); this._tracer.TraceException(exception2); return false; } try { int counterId = base._counterNameToIdMapping[counterName]; return this.GetCounterValue(counterId, isNumerator, out counterValue); } catch (KeyNotFoundException) { InvalidOperationException exception3 = new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Lookup for counter corresponding to counter name {0} failed", new object[] { counterName })); this._tracer.TraceException(exception3); return false; } }
void CleanupWaitQueue() { lock (((ICollection)wait_queue).SyncRoot) { if (wait_queue.Count == 0) return; var exc = new ObjectDisposedException (GetType ().ToString ()); foreach (var ares in wait_queue) { ares.Complete (exc); } wait_queue.Clear (); } }
private void SetDisposeExceptonToPenndingTask() { _log.WarnFormat("KafkaTcpSocket thread shutting down because of a dispose call."); var disposeException = new ObjectDisposedException("Object is disposing."); _sendTaskQueue.DrainAndApply(t => t.Tcp.TrySetException(disposeException)); _readTaskQueue.DrainAndApply(t => t.Tcp.TrySetException(disposeException)); }
private Exception WrappedException(Exception ex) { Exception wrappedException; if (_disposeToken.IsCancellationRequested) wrappedException = new ObjectDisposedException(string.Format("Object is disposing (KafkaTcpSocket for endpoint: {0})", Endpoint)); else wrappedException = new BrokerConnectionException(string.Format("Lost connection to server: {0}", _endpoint), _endpoint, ex); return wrappedException; }
private void SetDisposeExceptonToPenndingTasks(Exception exception = null) { var disposeException = new ObjectDisposedException("Object is disposing."); if (exception == null) { _log.WarnFormat("KafkaTcpSocket thread shutting down because of a dispose call."); _sendTaskQueue.DrainAndApply(t => t.Tcp.TrySetException(disposeException)); _readTaskQueue.DrainAndApply(t => t.Tcp.TrySetException(disposeException)); } else { _log.WarnFormat("KafkaTcpSocket not able to connect cancel all PenndingTasks."); _sendTaskQueue.DrainAndApply(t => t.Tcp.TrySetException(exception)); _readTaskQueue.DrainAndApply(t => t.Tcp.TrySetException(exception)); } }
/// <summary> /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException. /// and in winrt and marshal APIs as Exception. /// </summary> /// <param name="errorCode"></param> /// <param name="message"></param> /// <param name="createCOMException"></param> /// <returns></returns> internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo) { if (errorCode >= 0) { return null; } Exception exception = null; bool shouldDisplayHR = false; switch (errorCode) { case __HResults.COR_E_NOTFINITENUMBER: // NotFiniteNumberException case __HResults.COR_E_ARITHMETIC: exception = new ArithmeticException(); break; case __HResults.COR_E_ARGUMENT: case unchecked((int)0x800A01C1): case unchecked((int)0x800A01C2): case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT: exception = new ArgumentException(); if (errorCode != __HResults.COR_E_ARGUMENT) shouldDisplayHR = true; break; case __HResults.E_BOUNDS: case __HResults.COR_E_ARGUMENTOUTOFRANGE: case __HResults.ERROR_NO_UNICODE_TRANSLATION: exception = new ArgumentOutOfRangeException(); if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE) shouldDisplayHR = true; break; case __HResults.COR_E_ARRAYTYPEMISMATCH: exception = new ArrayTypeMismatchException(); break; case __HResults.COR_E_BADIMAGEFORMAT: case __HResults.CLDB_E_FILE_OLDVER: case __HResults.CLDB_E_INDEX_NOTFOUND: case __HResults.CLDB_E_FILE_CORRUPT: case __HResults.COR_E_NEWER_RUNTIME: case __HResults.COR_E_ASSEMBLYEXPECTED: case __HResults.ERROR_BAD_EXE_FORMAT: case __HResults.ERROR_EXE_MARKED_INVALID: case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT: case __HResults.ERROR_NOACCESS: case __HResults.ERROR_INVALID_ORDINAL: case __HResults.ERROR_INVALID_DLL: case __HResults.ERROR_FILE_CORRUPT: case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY: case __HResults.META_E_BAD_SIGNATURE: exception = new BadImageFormatException(); // Always show HR for BadImageFormatException shouldDisplayHR = true; break; case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT: exception = new FormatException(); break; // CustomAttributeFormatException case __HResults.COR_E_DATAMISALIGNED: exception = InteropExtensions.CreateDataMisalignedException(message); // TODO: Do we need to add msg here? break; case __HResults.COR_E_DIVIDEBYZERO: case __HResults.CTL_E_DIVISIONBYZERO: exception = new DivideByZeroException(); if (errorCode != __HResults.COR_E_DIVIDEBYZERO) shouldDisplayHR = true; break; case __HResults.COR_E_DLLNOTFOUND: #if ENABLE_WINRT exception = new DllNotFoundException(); #endif break; case __HResults.COR_E_DUPLICATEWAITOBJECT: exception = new ArgumentException(); break; // DuplicateWaitObjectException case __HResults.COR_E_ENDOFSTREAM: case unchecked((int)0x800A003E): exception = new System.IO.EndOfStreamException(); if (errorCode != __HResults.COR_E_ENDOFSTREAM) shouldDisplayHR = true; break; case __HResults.COR_E_TYPEACCESS: // TypeAccessException case __HResults.COR_E_ENTRYPOINTNOTFOUND: exception = new TypeLoadException(); break; // EntryPointNotFoundException case __HResults.COR_E_EXCEPTION: exception = new Exception(); break; case __HResults.COR_E_DIRECTORYNOTFOUND: case __HResults.STG_E_PATHNOTFOUND: case __HResults.CTL_E_PATHNOTFOUND: exception = new System.IO.DirectoryNotFoundException(); if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND) shouldDisplayHR = true; break; case __HResults.COR_E_FILELOAD: case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION: case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED: case __HResults.FUSION_E_LOADFROM_BLOCKED: case __HResults.FUSION_E_CACHEFILE_FAILED: case __HResults.FUSION_E_ASM_MODULE_MISSING: case __HResults.FUSION_E_INVALID_NAME: case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED: case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH: case __HResults.COR_E_MODULE_HASH_CHECK_FAILED: case __HResults.FUSION_E_REF_DEF_MISMATCH: case __HResults.SECURITY_E_INCOMPATIBLE_SHARE: case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE: case __HResults.SECURITY_E_UNVERIFIABLE: case __HResults.COR_E_FIXUPSINEXE: case __HResults.ERROR_TOO_MANY_OPEN_FILES: case __HResults.ERROR_SHARING_VIOLATION: case __HResults.ERROR_LOCK_VIOLATION: case __HResults.ERROR_OPEN_FAILED: case __HResults.ERROR_DISK_CORRUPT: case __HResults.ERROR_UNRECOGNIZED_VOLUME: case __HResults.ERROR_DLL_INIT_FAILED: case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED: case __HResults.CORSEC_E_MISSING_STRONGNAME: case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS: case __HResults.ERROR_FILE_INVALID: exception = new System.IO.FileLoadException(); shouldDisplayHR = true; break; case __HResults.COR_E_PATHTOOLONG: exception = new System.IO.PathTooLongException(); break; case __HResults.COR_E_IO: case __HResults.CTL_E_DEVICEIOERROR: case unchecked((int)0x800A793C): case unchecked((int)0x800A793D): exception = new System.IO.IOException(); if (errorCode != __HResults.COR_E_IO) shouldDisplayHR = true; break; case __HResults.ERROR_FILE_NOT_FOUND: case __HResults.ERROR_MOD_NOT_FOUND: case __HResults.ERROR_INVALID_NAME: case __HResults.CTL_E_FILENOTFOUND: case __HResults.ERROR_BAD_NET_NAME: case __HResults.ERROR_BAD_NETPATH: case __HResults.ERROR_NOT_READY: case __HResults.ERROR_WRONG_TARGET_NAME: case __HResults.INET_E_UNKNOWN_PROTOCOL: case __HResults.INET_E_CONNECTION_TIMEOUT: case __HResults.INET_E_CANNOT_CONNECT: case __HResults.INET_E_RESOURCE_NOT_FOUND: case __HResults.INET_E_OBJECT_NOT_FOUND: case __HResults.INET_E_DOWNLOAD_FAILURE: case __HResults.INET_E_DATA_NOT_AVAILABLE: case __HResults.ERROR_DLL_NOT_FOUND: case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW: case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH: case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND: exception = new System.IO.FileNotFoundException(); shouldDisplayHR = true; break; case __HResults.COR_E_FORMAT: exception = new FormatException(); break; case __HResults.COR_E_INDEXOUTOFRANGE: case unchecked((int)0x800a0009): exception = new IndexOutOfRangeException(); if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE) shouldDisplayHR = true; break; case __HResults.COR_E_INVALIDCAST: exception = new InvalidCastException(); break; case __HResults.COR_E_INVALIDCOMOBJECT: exception = new InvalidComObjectException(); break; case __HResults.COR_E_INVALIDOLEVARIANTTYPE: exception = new InvalidOleVariantTypeException(); break; case __HResults.COR_E_INVALIDOPERATION: case __HResults.E_ILLEGAL_STATE_CHANGE: case __HResults.E_ILLEGAL_METHOD_CALL: case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT: case __HResults.APPMODEL_ERROR_NO_PACKAGE: exception = new InvalidOperationException(); if (errorCode != __HResults.COR_E_INVALIDOPERATION) shouldDisplayHR = true; break; case __HResults.COR_E_MARSHALDIRECTIVE: exception = new MarshalDirectiveException(); break; case __HResults.COR_E_METHODACCESS: // MethodAccessException case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException case __HResults.COR_E_FIELDACCESS: case __HResults.COR_E_MEMBERACCESS: exception = new MemberAccessException(); if (errorCode != __HResults.COR_E_METHODACCESS) shouldDisplayHR = true; break; case __HResults.COR_E_MISSINGFIELD: // MissingFieldException case __HResults.COR_E_MISSINGMETHOD: // MissingMethodException case __HResults.COR_E_MISSINGMEMBER: case unchecked((int)0x800A01CD): exception = new MissingMemberException(); break; case __HResults.COR_E_MISSINGMANIFESTRESOURCE: exception = new System.Resources.MissingManifestResourceException(); break; case __HResults.COR_E_NOTSUPPORTED: case unchecked((int)0x800A01B6): case unchecked((int)0x800A01BD): case unchecked((int)0x800A01CA): case unchecked((int)0x800A01CB): exception = new NotSupportedException(); if (errorCode != __HResults.COR_E_NOTSUPPORTED) shouldDisplayHR = true; break; case __HResults.COR_E_NULLREFERENCE: exception = new NullReferenceException(); break; case __HResults.COR_E_OBJECTDISPOSED: case __HResults.RO_E_CLOSED: // No default constructor exception = new ObjectDisposedException(String.Empty); break; case __HResults.COR_E_OPERATIONCANCELED: #if ENABLE_WINRT exception = new OperationCanceledException(); #endif break; case __HResults.COR_E_OVERFLOW: case __HResults.CTL_E_OVERFLOW: exception = new OverflowException(); break; case __HResults.COR_E_PLATFORMNOTSUPPORTED: exception = new PlatformNotSupportedException(message); break; case __HResults.COR_E_RANK: exception = new RankException(); break; case __HResults.COR_E_REFLECTIONTYPELOAD: #if ENABLE_WINRT exception = new System.Reflection.ReflectionTypeLoadException(null, null); #endif break; case __HResults.COR_E_SECURITY: case __HResults.CORSEC_E_INVALID_STRONGNAME: case __HResults.CTL_E_PERMISSIONDENIED: case unchecked((int)0x800A01A3): case __HResults.CORSEC_E_INVALID_PUBLICKEY: case __HResults.CORSEC_E_SIGNATURE_MISMATCH: exception = new System.Security.SecurityException(); break; case __HResults.COR_E_SAFEARRAYRANKMISMATCH: exception = new SafeArrayRankMismatchException(); break; case __HResults.COR_E_SAFEARRAYTYPEMISMATCH: exception = new SafeArrayTypeMismatchException(); break; case __HResults.COR_E_SERIALIZATION: exception = new System.Runtime.Serialization.SerializationException(message); break; case __HResults.COR_E_SYNCHRONIZATIONLOCK: exception = new System.Threading.SynchronizationLockException(); break; case __HResults.COR_E_TARGETINVOCATION: exception = new System.Reflection.TargetInvocationException(null); break; case __HResults.COR_E_TARGETPARAMCOUNT: exception = new System.Reflection.TargetParameterCountException(); break; case __HResults.COR_E_TYPEINITIALIZATION: exception = InteropExtensions.CreateTypeInitializationException(message); break; case __HResults.COR_E_TYPELOAD: case __HResults.RO_E_METADATA_NAME_NOT_FOUND: case __HResults.CLR_E_BIND_TYPE_NOT_FOUND: exception = new TypeLoadException(); if (errorCode != __HResults.COR_E_TYPELOAD) shouldDisplayHR = true; break; case __HResults.COR_E_UNAUTHORIZEDACCESS: case __HResults.CTL_E_PATHFILEACCESSERROR: case unchecked((int)0x800A014F): exception = new UnauthorizedAccessException(); shouldDisplayHR = true; break; case __HResults.COR_E_VERIFICATION: exception = new System.Security.VerificationException(); break; case __HResults.E_NOTIMPL: exception = new NotImplementedException(); break; case __HResults.E_OUTOFMEMORY: case __HResults.CTL_E_OUTOFMEMORY: case unchecked((int)0x800A7919): exception = new OutOfMemoryException(); if (errorCode != __HResults.E_OUTOFMEMORY) shouldDisplayHR = true; break; #if ENABLE_WINRT case __HResults.E_XAMLPARSEFAILED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTAVAILABLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTENABLED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_LAYOUTCYCLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; #endif // ENABLE_WINRT case __HResults.COR_E_AMBIGUOUSMATCH: // AmbiguousMatchException case __HResults.COR_E_APPLICATION: // ApplicationException case __HResults.COR_E_APPDOMAINUNLOADED: // AppDomainUnloadedException case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN: // CannotUnloadAppDomainException case __HResults.COR_E_CODECONTRACTFAILED: // ContractException case __HResults.COR_E_CONTEXTMARSHAL: // ContextMarshalException case __HResults.CORSEC_E_CRYPTO: // CryptographicException case __HResults.CORSEC_E_CRYPTO_UNEX_OPER: // CryptographicUnexpectedOperationException case __HResults.COR_E_EXECUTIONENGINE: // ExecutionEngineException case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException case __HResults.COR_E_INVALIDFILTERCRITERIA: // InvalidFilterCriteriaException case __HResults.COR_E_INVALIDPROGRAM: // InvalidProgramException case __HResults.COR_E_MULTICASTNOTSUPPORTED: // MulticastNotSupportedException case __HResults.COR_E_REMOTING: // RemotingException case __HResults.COR_E_RUNTIMEWRAPPED: // RuntimeWrappedException case __HResults.COR_E_SERVER: // ServerException case __HResults.COR_E_STACKOVERFLOW: // StackOverflowException case __HResults.CTL_E_OUTOFSTACKSPACE: // StackOverflowException case __HResults.COR_E_SYSTEM: // SystemException case __HResults.COR_E_TARGET: // TargetException case __HResults.COR_E_THREADABORTED: // TargetException case __HResults.COR_E_THREADINTERRUPTED: // ThreadInterruptedException case __HResults.COR_E_THREADSTATE: // ThreadStateException case __HResults.COR_E_THREADSTART: // ThreadStartException case __HResults.COR_E_TYPEUNLOADED: // TypeUnloadedException case __HResults.CORSEC_E_POLICY_EXCEPTION: // PolicyException case __HResults.CORSEC_E_NO_EXEC_PERM: // PolicyException case __HResults.CORSEC_E_MIN_GRANT_FAIL: // PolicyException case __HResults.CORSEC_E_XMLSYNTAX: // XmlSyntaxException case __HResults.ISS_E_ALLOC_TOO_LARGE: // IsolatedStorageException case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL: // IsolatedStorageException case __HResults.ISS_E_CALLER: // IsolatedStorageException case __HResults.ISS_E_CORRUPTED_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_CREATE_DIR: // IsolatedStorageException case __HResults.ISS_E_CREATE_MUTEX: // IsolatedStorageException case __HResults.ISS_E_DEPRECATE: // IsolatedStorageException case __HResults.ISS_E_FILE_NOT_MAPPED: // IsolatedStorageException case __HResults.ISS_E_FILE_WRITE: // IsolatedStorageException case __HResults.ISS_E_GET_FILE_SIZE: // IsolatedStorageException case __HResults.ISS_E_ISOSTORE: // IsolatedStorageException case __HResults.ISS_E_LOCK_FAILED: // IsolatedStorageException case __HResults.ISS_E_MACHINE: // IsolatedStorageException case __HResults.ISS_E_MACHINE_DACL: // IsolatedStorageException case __HResults.ISS_E_MAP_VIEW_OF_FILE: // IsolatedStorageException case __HResults.ISS_E_OPEN_FILE_MAPPING: // IsolatedStorageException case __HResults.ISS_E_OPEN_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_PATH_LENGTH: // IsolatedStorageException case __HResults.ISS_E_SET_FILE_POINTER: // IsolatedStorageException case __HResults.ISS_E_STORE_NOT_OPEN: // IsolatedStorageException case __HResults.ISS_E_STORE_VERSION: // IsolatedStorageException case __HResults.ISS_E_TABLE_ROW_NOT_FOUND: // IsolatedStorageException case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA: // IsolatedStorageException case __HResults.E_FAIL: default: break; } if (exception == null) { if (createCOMException) { exception = new COMException(); if (errorCode != __HResults.E_FAIL) shouldDisplayHR = true; } else { exception = new Exception(); if (errorCode != __HResults.COR_E_EXCEPTION) shouldDisplayHR = true; } } bool shouldConstructMessage = false; if (hasErrorInfo) { // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if // the message is not available and do not use the shouldDisplayHR setting if (message == null) shouldConstructMessage = true; } else { // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above shouldConstructMessage = shouldDisplayHR; } if (shouldConstructMessage) { // // Append the HR into error message, just in case the app wants to look at the HR in // message to determine behavior. We didn't expose HResult property until v4.5 and // GetHRFromException has side effects so probably Message was their only choice. // This behavior is probably not exactly the same as in desktop but it is fine to append // more message at the end. In any case, having the HR in the error message are helpful // to developers. // This makes sure: // 1. We always have a HR 0xNNNNNNNN in the message // 2. Put in a nice "Exception thrown from HRESULT" message if we can // 3. Wrap it in () if there is an existing message // // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString()); message = ExternalInterop.GetMessage(errorCode); // Always make sure we have at least the HRESULT part in retail build or when the message // is empty. if (message == null) message = hrMessage; else message = message + " (" + hrMessage + ")"; } if (message != null) { // Set message explicitly rather than calling constructor because certain ctors would append a // prefix to the message and that is not what we want InteropExtensions.SetExceptionMessage(exception, message); } InteropExtensions.SetExceptionErrorCode(exception, errorCode); return exception; }
void Cleanup(bool closeExisting) { lock (_registry) { if (closeExisting) { // Need to copy this since closing will call UnregisterContext var keys = _registry.Keys; var all = new HttpListenerContext[keys.Count]; keys.CopyTo(all, 0); _registry.Clear(); for (var i = all.Length - 1; i >= 0; i--) all[i].Connection.Close(true); } lock (_connections.SyncRoot) { var keys = _connections.Keys; var conns = new HttpConnection[keys.Count]; keys.CopyTo(conns, 0); _connections.Clear(); for (var i = conns.Length - 1; i >= 0; i--) conns[i].Close(true); } lock (_ctxQueue) { var ctxs = (HttpListenerContext[])_ctxQueue.ToArray(typeof(HttpListenerContext)); _ctxQueue.Clear(); for (var i = ctxs.Length - 1; i >= 0; i--) ctxs[i].Connection.Close(true); } lock (_waitQueue) { Exception exc = new ObjectDisposedException("listener"); foreach (ListenerAsyncResult ares in _waitQueue) { ares.Complete(exc); } _waitQueue.Clear(); } } }
/// <summary> /// Dispose the connection manager /// </summary> /// <param name="isDisposing"></param> protected void Dispose(bool isDisposing) { if (_isDisposed || !isDisposing) return; lock (_syncObject) { if (_isDisposed) return; _isDisposing = true; // set these values to servicing so that a thread is // not started Interlocked.CompareExchange(ref _isServicing, Servicing, NotServicing); Interlocked.CompareExchange(ref _isServicingCallbacks, Servicing, NotServicing); Interlocked.CompareExchange(ref _isServicingCleanups, Servicing, NotServicing); Interlocked.CompareExchange(ref _timerFired, TimerFired, TimerReset); // close and clear all connections in connection pool ClearAll(); // This should be done after closing all connections. // Throttling thread executes the close operations Interlocked.CompareExchange(ref _isOperationsServiced, Servicing, NotServicing); _timer.Elapsed -= HandleTimerElapsed; _timer.Dispose(); var objectDisposedException = new ObjectDisposedException("ConnectionManager"); GetRunspaceAsyncResult item; while (_callbacks.TryDequeue(out item)) { item.SetAsCompleted(objectDisposedException); } _cleanupComputers.Clear(); RequestInfo info; while (_inComingRequests.Count > 0) { _inComingRequests.TryDequeue(out info); info.AsyncResult.SetAsCompleted(objectDisposedException); } foreach(var reqInfo in _pendingRequests) { reqInfo.AsyncResult.SetAsCompleted(objectDisposedException); } _pendingRequests.Clear(); ThrottleOperation operation; while (_pendingQueue.Count > 0) { _pendingQueue.TryDequeue(out operation); } _timerMap.Clear(); _servicingThreadRelease.Close(); _timerThreadRelease.Close(); _testHelperCloseDone.Close(); _tracer.Dispose(); _isDisposed = true; } }
internal static ObjectDisposedException ObjectDisposed(object instance) { ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name); TraceExceptionAsReturnValue(e); return e; }