관리되지 않는 리소스를 안전하게 정리하기 위해 IDisposable 인터페이스를 활용해보자.
IDisposable 을 구현한 객체에서 Dispose() 메서드를 구현하여
사용 후 리소스를 해제하기 위해 사용한다.
namespace System
{
public interface IDisposable
{
void Dispose();
}
}
IDisposable 객체를 { } 에서 사용한 뒤 자동으로 Dispose() 를 호출해주는 문법
public class Example : IDisposable { }
using(var ex = new Example())
{
// ex 사용
}
// Dispose() 자동 호출
public class ResourcesLoad : IDisposable
{
public void Connect()
{
Console.WriteLine("리소스 연결");
}
public void Disconnect()
{
Console.WriteLine("리소스 해제");
}
public void Dispose()
{
Disconnect();
}
}
static void Main(string[] args)
{
Console.WriteLine("IDisposable\n");
using (ResourcesLoad resourcesLoad = new ResourcesLoad())
{
resourcesLoad.Connect();
Console.WriteLine("리소스 사용 끝");
}
}
XML을 순차적으로 작성하는 클래스인 XmlWriter 를 using 과 함께 사용할 수 있다.
XmlWriter 는 IDisposable 을 상속하고 있다.
using(XmlWriter xml = XmlWriter.Create(xmlFilePath + xmlFileName))
{
xml.WriteStartDocument();
xml.WriteStartElement(EFFECT);
xml.WriteElementString("length", GetDataCount().ToString());
for (int i = 0; i < this.names.Length; i++)
{
EffectClip clip = this.effectClips[i];
xml.WriteStartElement(CLIP);
xml.WriteElementString("id", i.ToString());
xml.WriteElementString("name", names[i]);
xml.WriteElementString("effectType", clip.effectType.ToString());
xml.WriteElementString("effectPath", clip.effectPath);
xml.WriteElementString("effectName", clip.effectName);
xml.WriteEndElement();
}
xml.WriteEndElement();
xml.WriteEndDocument();
} // Dispose() 자동 호출
아래와 같은 형식으로 xml 파일이 저장된다.
using 블록이 종료되면, 컴파일러에서 xml.Dispose() 를 호출하고
xml 객체는 더 이상 유효하지 않는다.
IDisposable 을 상속 받은 외부 라이브러리를 사용하는 경우, using 문을 활용하여
자동으로 Dispose() 를 호출하게 유도해보자.