using 陳述式
資源釋放
緣起:
當使用封裝資源的物件,常需要在使用結束後或例外發生時,移除資源。
方式:
使用using 與IDisposable 介面
使用前:
XXXresource resource = null;
try
{
resource = new XXXresource();
//resource do something
….
}
catch(Exception ex)
{
//輸出訊息
}
finally
{
resource.Quit();
resource.Close();
}
使用後:
using(XXXresource resource= new XXXresource())
{
//resource do something
}
Example:
//封裝wordApp
class ExportWord :IDisposable
{
Microsoft.Office.Interop.Word.Application _wordApp = null;
public ExportWord()
{
try
{
_wordApp = new Microsoft.Office.Interop.Word.Application();
}
catch (Exception)
{
Utilities.ShowErrorMessage(DCMSConfigurationType.RoleDocument, "Err_012");
}
}
public ExportWord(Microsoft.Office.Interop.Word.Application pWordApp)
{
_wordApp = pWordApp;
}
public Microsoft.Office.Interop.Word.Application WordApp
{
get
{
return _wordApp;
}
}
public bool CanDispose
{
get;
set;
}
public Microsoft.Office.Interop.Word.Document OpenFile(string pFileName)
{
object missing = System.Reflection.Missing.Value;
object fileName = pFileName;
return WordApp.Documents.Open(ref fileName,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing);
}
#region IDisposable 成員
public void Dispose()
{
if (CanDispose && _wordApp != null && _wordApp.Visible == true)
{
object missingParameter = System.Reflection.Missing.Value;
_wordApp.Quit(ref missingParameter, ref missingParameter, ref missingParameter);
_wordApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
#endregion
}
注意事項:
- using 需搭配有實作IDisposable 的類別
- using內 ,需自行catch exception 處理例外
其他:
如有管理資源的需求時,例如於表單關閉時,移除資源使用,可參考
http://msdn.microsoft.com/zh-tw/library/d9yzd5cx(VS.80).aspx
實作Dispose
http://msdn.microsoft.com/zh-tw/library/fs2xkftw(VS.80).aspx
Using
http://msdn.microsoft.com/zh-tw/library/3bwa4xa9(VS.80).aspx