網站首頁 編程語言 正文
一、常見非托管資源
- Windows窗口句柄、數據庫鏈接、GDI對象、獨占文件鎖等等對象
- ApplicationContext,Brush,Component,ComponentDesigner,Container,Context,Cursor
- FileStream,Font,Icon,Image,Matrix,Object,OdbcDataReader,OleDBDataReader,Pen
- Regex,Socket,StreamWriter,Timer,Tooltip
二、實現原理
定義類繼承IDisposable
接口
public class DisposeTest : IDisposable { //實現IDisposable接口方法 public void Dispose() { } }
在類中定義資源和方法
public class DisposeTest : IDisposable { #region Dispose經典實現方式 //實現IDisposable接口方法 public void Dispose() { Dispose(true);//調用處理方法 GC.SuppressFinalize(this);//讓GC忽略 } //資源 private readonly IntPtr unmanagedResource;//非托管內存 private readonly SafeHandle managedResource;//托管資源 //構造方法初始化資源 public DisposeTest() { unmanagedResource = Marshal.AllocHGlobal(sizeof(int));//分配非托管內存 managedResource = new SafeFileHandle(new IntPtr(), true);//創建托管資源 } //根據不同資源進行處理 protected virtual void Dispose(bool isManualDisposing) { ReleaseUnmanagedResourse(unmanagedResource);//處理非托管資源 if (isManualDisposing) { ReleaseManagedResources(managedResource);//處理托管資源 } } private void ReleaseUnmanagedResourse(IntPtr intPtr) { Marshal.FreeHGlobal(intPtr); //釋放非托管內存 } private void ReleaseManagedResources(SafeHandle safeHandle) { if (safeHandle != null) { safeHandle.Dispose(); //釋放托管資源 } } //析構函數處理托管資源 ~DisposeTest() { Dispose(false); } #endregion }
三、Close()和Dispose()區別
- lose()方法關閉對象,沒有完全釋放。Dispose()方法完全釋放了
- 一般情況,Close() 實現了接口對Dispose()的封裝,調用時不需要直接調用Dispose()
四、常見封裝的語法寫法
Close()方法
SqlConnection conn3 = new SqlConnection(); try { conn3.Open(); } catch (Exception) { throw; } finally { conn3.Close();//關閉對象 }
using()
using (SqlConnection cnn = new SqlConnection()) { //此處使用,使用完后系統會自動釋放 }
Dispose()
SqlConnection cnn2 = new SqlConnection(); try { //這里寫要執行的代碼 } finally { cnn2.Dispose(); }
原文鏈接:https://www.cnblogs.com/wml-it/p/16081656.html
相關推薦
- 2022-05-15 C++?Clock類模擬實現鬧鐘運行_C 語言
- 2024-07-18 Spring Security之基于方法配置權限
- 2023-05-21 Golang?flag包的具體使用_Golang
- 2022-04-20 Python?設計模式中命令模式_python
- 2022-06-22 c++分離講解模板的概念與使用_C 語言
- 2023-02-26 詳解flutter如何實現局部導航管理_Android
- 2022-04-18 WPF使用代碼創建數據模板DataTemplate_實用技巧
- 2022-04-30 python?format格式化和數字格式化_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支