在DC属于Service类属性的情况下,如何处理DC?
class Service()
{
public DataContext DC= new DataContext();
public void SomeMethod()
{
DC is used here.
}
public void SomeOtherMethod()
{
DC is also used here.
}
}
答案 0 :(得分:6)
如果“服务”类维护对非托管资源的引用,则应该实现IDisposable。这告诉您的类的客户端他们需要在“服务”的实例上调用Dispose()。您可以在类'Dispose()方法中调用“DC”上的Dispose()。
class Service : IDisposable
{
public DataContext DC= new DataContext();
public void Dispose( )
{
DC.Dispose( );
}
}
顺便说一句,我会避免在C#中创建公共字段,其中属性是常见的习惯用法。
答案 1 :(得分:1)
使您的服务IDIposposable并在Dispose方法中处理DataContext。这是一种常见的模式。
答案 2 :(得分:1)
您可以在托管类上实现IDisposable并在Dispose()方法中处置托管DC。然后使用'using'..
使用托管类using(Service service = new Service())
{
// do something with "service" here
}
答案 3 :(得分:1)
您的Service类应该处理DataContext。
使用标准Dispose pattern。
答案 4 :(得分:1)
实施IDisposable: MSDN: Implementing a Dispose Method
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// If you need thread safety, use a lock around these
// operations, as well as in your methods that use the resource.
if (!_disposed)
{
if (disposing) {
if (DC != null)
DC.Dispose();
}
// Indicate that the instance has been disposed.
DC = null;
_disposed = true;
}
}