Example #1
0
 protected virtual void DisposeManagedResources()
 {
     if (_handle != null)
     {
         _handle.Dispose();
     }
 }
        internal override void Dispose()
        {
            SafeHandle packetHandle    = _sniPacket;
            SafeHandle sessionHandle   = _sessionHandle;
            SafeHandle asyncAttnPacket = _sniAsyncAttnPacket;

            _sniPacket          = null;
            _sessionHandle      = null;
            _sniAsyncAttnPacket = null;

            DisposeCounters();

            if (null != sessionHandle || null != packetHandle)
            {
                packetHandle?.Dispose();
                asyncAttnPacket?.Dispose();

                if (sessionHandle != null)
                {
                    sessionHandle.Dispose();
                    DecrementPendingCallbacks(true); // Will dispose of GC handle.
                }
            }

            DisposePacketCache();
        }
Example #3
0
        public static bool IsFileInUse(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return(false);
            }

            SafeHandle handleValue = null;

            try
            {
                handleValue = CreateFile(filePath, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

                bool inUse = handleValue.IsInvalid;

                return(inUse);
            }
            finally
            {
                if (handleValue != null)
                {
                    handleValue.Close();

                    handleValue.Dispose();

                    handleValue = null;
                }
            }
        }
        public static SafeHandle GetTokenInformation(SafeCloseHandle token, TOKEN_INFORMATION_CLASS infoClass)
        {
            uint num;

            if (!SafeNativeMethods.GetTokenInformation(token, infoClass, SafeHGlobalHandle.InvalidHandle, 0, out num))
            {
                int error = Marshal.GetLastWin32Error();
                if (error != 0x7a)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, System.ServiceModel.SR.GetString("GetTokenInfoFailed", new object[] { error })));
                }
            }
            SafeHandle tokenInformation = SafeHGlobalHandle.AllocHGlobal(num);

            try
            {
                if (!SafeNativeMethods.GetTokenInformation(token, infoClass, tokenInformation, num, out num))
                {
                    int num3 = Marshal.GetLastWin32Error();
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(num3, System.ServiceModel.SR.GetString("GetTokenInfoFailed", new object[] { num3 })));
                }
            }
            catch
            {
                tokenInformation.Dispose();
                throw;
            }
            return(tokenInformation);
        }
Example #5
0
 private void ReleaseUnmanagedResources(SafeHandle safeHandle)
 {
     if (safeHandle != null)
     {
         safeHandle.Dispose();
     }
 }
Example #6
0
        private SafeCreateHandle PreparePoliciesArray(bool checkRevocation)
        {
            IntPtr[] policies = new IntPtr[checkRevocation ? 2 : 1];

            SafeHandle defaultPolicy = Interop.AppleCrypto.X509ChainCreateDefaultPolicy();

            if (defaultPolicy.IsInvalid)
            {
                defaultPolicy.Dispose();
                throw new PlatformNotSupportedException(nameof(X509Chain));
            }

            _extraHandles.Push(defaultPolicy);
            policies[0] = defaultPolicy.DangerousGetHandle();

            if (checkRevocation)
            {
                SafeHandle revPolicy = Interop.AppleCrypto.X509ChainCreateRevocationPolicy();
                _extraHandles.Push(revPolicy);
                policies[1] = revPolicy.DangerousGetHandle();
            }

            SafeCreateHandle policiesArray =
                Interop.CoreFoundation.CFArrayCreate(policies, (UIntPtr)policies.Length);

            _extraHandles.Push(policiesArray);
            return(policiesArray);
        }
    [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
    public unsafe void SingleOperationOverSingleHandle()
    {
        const int DATA_SIZE = 2;

        SafeHandle            handle      = HandleFactory.CreateAsyncFileHandleForWrite(Path.Combine(TestDirectory, @"SingleOverlappedOverSingleHandle.tmp"));
        ThreadPoolBoundHandle boundHandle = ThreadPoolBoundHandle.BindHandle(handle);

        OverlappedContext result = new OverlappedContext();

        byte[] data = new byte[DATA_SIZE];
        data[0] = (byte)'A';
        data[1] = (byte)'B';

        NativeOverlapped *overlapped = boundHandle.AllocateNativeOverlapped(OnOverlappedOperationCompleted, result, data);

        fixed(byte *p = data)
        {
            int retval = DllImport.WriteFile(boundHandle.Handle, p, DATA_SIZE, IntPtr.Zero, overlapped);

            if (retval == 0)
            {
                Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error());
            }

            // Wait for overlapped operation to complete
            result.Event.WaitOne();
        }

        boundHandle.FreeNativeOverlapped(overlapped);
        boundHandle.Dispose();
        handle.Dispose();

        Assert.Equal(0, result.ErrorCode);
        Assert.Equal(DATA_SIZE, result.BytesWritten);
    }
Example #8
0
        public unsafe void CloseRequestQueueHandle()
        {
            lock (this)
            {
                if (!RequestQueueHandle.IsInvalid)
                {
                    if (NetEventSource.IsEnabled)
                    {
                        NetEventSource.Info($"Dispose ThreadPoolBoundHandle: {_requestQueueBoundHandle}");
                    }
                    _requestQueueBoundHandle?.Dispose();
                    RequestQueueHandle.Dispose();

                    // CancelIoEx is called after Dispose to prevent a race condition involving parallel GetContext and
                    // HttpReceiveHttpRequest calls. Otherwise, calling CancelIoEx before Dispose might block the synchronous
                    // GetContext call until the next request arrives.
                    try
                    {
                        Interop.Kernel32.CancelIoEx(RequestQueueHandle, null); // This cancels the synchronous call to HttpReceiveHttpRequest
                    }
                    catch (ObjectDisposedException)
                    {
                        // Ignore the exception since it only means that the queue handle has been successfully disposed
                    }
                }
            }
        }
Example #9
0
        // Protected implementation of Dispose pattern.
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                handle.Dispose();
                // Free any other managed objects here.
                //
                _zones           = null;
                _validaties      = null;
                _kinds           = null;
                _categories      = null;
                _subzones        = null;
                _subkinds        = null;
                _managements     = null;
                _aprovals_states = null;
                _origins         = null;
                _type_assets     = null;
                _parameters      = null;
                _documents       = null;
                _systems         = null;
                _sys_params      = null;

                _context.Dispose();//  = null;
            }

            disposed = true;
        }
Example #10
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         // In 4.0, there is a memory leak due to a cycle going through
         // native code that the GC cannot detect.
         //
         // When someone derives from BitmapSource, WPF creates an
         // instance of the ManagedBitmapSource class to implement the
         // actual IWicBitmapSource interface for MIL to use.  WPF uses
         // COM interop (Marshal.GetComInterfaceForObject) to cast the
         // ManagedBitmapSource to the COM interface.  This pins the
         // ManagedBitmapSource behind the reference-counted COM interface,
         // which is then stored in a BitmapSourceSafeMILHandle, which is
         // held by the original BitmapSource instance.  The pinned
         // ManagedBitmapSource also holds a reference to the orginal
         // BitmapSource, thus a cycle is created that cannot be broken
         // by the GC.  It looks like this:
         //
         // CustomBitmapSource -->
         //   BitmapSourceSafeMILHandle (ref counted) -->
         //     ManagedBitmapSource -->
         //       CustomBitmapSource
         //
         // WPF will fix this in the future.  For now, we will use
         // private reflection to break the cycle explicitly.
         var        _wicSource = this.GetType().GetField("_wicSource", BindingFlags.NonPublic | BindingFlags.Instance);
         SafeHandle handle     = _wicSource.GetValue(this) as SafeHandle;
         if (handle != null && !handle.IsInvalid)
         {
             handle.Dispose();
             _wicSource.SetValue(this, null);
         }
     }
 }
Example #11
0
        // Protected implementation of Dispose pattern.
        public void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                handle.Dispose();

                if (mainMenuItems != null)
                {
                    foreach (var item in mainMenuItems)
                    {
                        item.Click -= radialMenuitem_Click;
                    }
                }

                if (alignMenuItems != null)
                {
                    foreach (var item in alignMenuItems)
                    {
                        item.Click -= radialMenuitem_Click;
                    }
                }
            }

            disposed = true;
        }
Example #12
0
 public static void TryDispose(this SafeHandle handle)
 {
     if ((handle != null) && !handle.IsClosed)
     {
         handle.Dispose();
     }
 }
Example #13
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         handle.Dispose();
     }
 }
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }
            if (disposing)
            {
                handle.Dispose();

                VoiceSendThread.Abort();
                UDPKeepAliveThread.Abort();
                WebsocketKeepAliveThread.Abort();

                Connected = false;
                if (VoiceWebSocket != null)
                {
                    VoiceWebSocket.Closed -= VoiceWebSocket_OnClose;
                    VoiceWebSocket.Error  -= VoiceWebSocket_OnError;
                    VoiceWebSocket.Close();
                }
                VoiceWebSocket = null;
                globalTaskSource.Cancel(false);
                globalTaskSource.Dispose();
                if (_udp != null)
                {
                    _udp.Close();
                }
                _udp = null;
            }
            disposed = true;
        }
Example #15
0
 // ✓ DO declare a protected virtual void Dispose(bool disposing) method to centralize
 // all logic related to releasing unmanaged resources.
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         resource?.Dispose();
     }
 }
Example #16
0
        protected virtual void Dispose(bool _Disposing)
        {
            if (IsDisposed)
            {
                return;
            }

            if (_Disposing)
            {
                handle.Dispose();
                if (ServerListener != null)
                {
                    ServerListener.Stop();
                }
                if (ClientSocket != null)
                {
                    ClientSocket.Close();
                }
                if (ServerRunning)
                {
                    ServerRunning = false;
                }
                while (!ServerEnded)
                {
                    Application.DoEvents();
                    Thread.Sleep(100);
                }
                if (ServerThread != null)
                {
                    ServerThread.Abort();
                }
            }

            IsDisposed = true;
        }
        /// <summary>
        /// Protected implementation of Dispose pattern
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                handle.Dispose();
                // Free any other managed objects here.
                adc?.Dispose();
                adc = null;

                dac?.Dispose();
                dac = null;

                IOi2cbus?.Dispose();
                IOi2cbus = null;

                RTCi2cbus?.Dispose();
                RTCi2cbus = null;

                IsConnected = false;
            }

            // Free any unmanaged objects here.
            //
            disposed = true;
        }
Example #18
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         // cleanup managed resources
     }
     _nativeOption.Dispose();
 }
Example #19
0
 public void Dispose()
 {
     if (Handle != null)
     {
         Handle.Dispose();
     }
     GC.SuppressFinalize(this);
 }
Example #20
0
 protected virtual void Dispose(bool disposing)
 {
     handle.Dispose();
     ReleaseObject(ExcelApp);
     ReleaseObject(ExcelWorkBook);
     ReleaseObject(ExcelSheet);
     Console.WriteLine("Excel Wrapper finalizer called");
 }
        public void Dispose()
        {
            _managedResource?.Dispose();
            // ? - if not null
            // if (_managedResource != null)
            //     _managedResource.Dispose();

            GC.SuppressFinalize(this);
        }
Example #22
0
 internal static void CheckValidOpenSslHandle(SafeHandle handle)
 {
     if (handle == null || handle.IsInvalid)
     {
         Exception e = CreateOpenSslCryptographicException();
         handle?.Dispose();
         throw e;
     }
 }
 protected virtual void Dispose(bool disposing)
 {
     if (disposed)
         return;
     mstream.Dispose();
     if (disposing)
         handle.Dispose();
     disposed = true;
 }
Example #24
0
 public void Close()
 {
     if (IsOpen())
     {
         hidHideHandle.Close();
         hidHideHandle.Dispose();
         hidHideHandle = null;
     }
 }
Example #25
0
 public TestClass()
 {
     DisposeService = new DisposeService <TestClass>(this, ps => { if (_handle != null)
                                                                   {
                                                                       _handle.Dispose();
                                                                   }
                                                     });
     _handle = new SafeFileHandle(IntPtr.Zero, true);
 }
Example #26
0
     protected virtual void Dispose(bool disposing)
     {
         ReleaseBuffer(buffer); // release unmanaged memory
     if (disposing)
     { 
         // release other disposable objects
         if (resource!= null)
            resource.Dispose();
     }
 }
Example #27
0
        public void Dispose()
        {
            if (disposed)
            {
                return;
            }

            handle.Dispose();
            disposed = true;
        }
Example #28
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (resource != null)
         {
             resource.Dispose();
         }
     }
 }
Example #29
0
 public void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (resource != null)
         {
             resource.Dispose();
         }
     }
 }
    [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
    public unsafe void MultipleOperationsOverSingleHandle()
    {
        const int DATA_SIZE = 2;

        SafeHandle            handle      = HandleFactory.CreateAsyncFileHandleForWrite(Path.Combine(TestDirectory, @"MultipleOperationsOverSingleHandle.tmp"));
        ThreadPoolBoundHandle boundHandle = ThreadPoolBoundHandle.BindHandle(handle);

        OverlappedContext result1 = new OverlappedContext();
        OverlappedContext result2 = new OverlappedContext();

        byte[] data1 = new byte[DATA_SIZE];
        data1[0] = (byte)'A';
        data1[1] = (byte)'B';


        byte[] data2 = new byte[DATA_SIZE];
        data2[0] = (byte)'C';
        data2[1] = (byte)'D';

        NativeOverlapped *overlapped1 = boundHandle.AllocateNativeOverlapped(OnOverlappedOperationCompleted, result1, data1);
        NativeOverlapped *overlapped2 = boundHandle.AllocateNativeOverlapped(OnOverlappedOperationCompleted, result2, data2);

        fixed(byte *p1 = data1, p2 = data2)
        {
            int retval = DllImport.WriteFile(boundHandle.Handle, p1, DATA_SIZE, IntPtr.Zero, overlapped1);

            if (retval == 0)
            {
                Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error());
            }


            // Start the offset after the above write, so that it doesn't overwrite the previous write
            overlapped2->OffsetLow = DATA_SIZE;
            retval = DllImport.WriteFile(boundHandle.Handle, p2, DATA_SIZE, IntPtr.Zero, overlapped2);

            if (retval == 0)
            {
                Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error());
            }

            // Wait for overlapped operations to complete
            WaitHandle.WaitAll(new WaitHandle[] { result1.Event, result2.Event });
        }

        boundHandle.FreeNativeOverlapped(overlapped1);
        boundHandle.FreeNativeOverlapped(overlapped2);
        boundHandle.Dispose();
        handle.Dispose();

        Assert.Equal(0, result1.ErrorCode);
        Assert.Equal(0, result2.ErrorCode);
        Assert.Equal(DATA_SIZE, result1.BytesWritten);
        Assert.Equal(DATA_SIZE, result2.BytesWritten);
    }