C#:实现IDisposable接口时Dispose方法的内容应该是什么
我创建了一个实现IDisposable接口的类,VisualStudio IDE为我带来了Dispose方法。我想知道我应该在 Dispose 方法中编写什么代码,以便它能够处理我的内存管理或它应该做的任何事情。
public class ESNVerification : IDisposable
{
public bool Save(string a,string b)
{
//Save the data to table
return true;
}
public void Dispose()
{
throw new NotImplementedException();
// Really what i should do here ?
}
}
I created a class which implements IDisposable interface and VisualStudio IDE brought the Dispose method for me. I am wondering what code i should write inside the Dispose method so that it will take care of my memory management or whatever stuff it should do.
public class ESNVerification : IDisposable
{
public bool Save(string a,string b)
{
//Save the data to table
return true;
}
public void Dispose()
{
throw new NotImplementedException();
// Really what i should do here ?
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
我建议如何实施三个简单规则 I一次性;此处简化为:
IDisposable
)资源。IDisposable
的此实现应该只为每个拥有的资源调用Dispose
。该类不应该有终结器。I recommend Three Simple Rules for how to implement IDisposable; simplified here:
IDisposable
does need to be implemented: The class owns an unmanaged resource or The class owns managed (IDisposable
) resources.IDisposable
(but not a finalizer). This implementation ofIDisposable
should only callDispose
for each owned resource. The class should not have a finalizer.IDisposable
and a finalizer.除非您正在使用某种需要清理的非托管资源(在这个极其简单的情况下,您不需要清理),那么您确实没有理由实现
IDisposable
。IDisposable
接口的 MSDN 描述中的第一行:如果您使用非托管资源,则可以使用 Dispose 方法确保正确释放这些资源(垃圾收集器将为您处理所有托管资源)。
Unless you're working with some kind of un-managed resources that need to be cleaned up (which, in this extremely simple case, you're not) then you really have no reason to implement
IDisposable
.The first line in the MSDN Description of the
IDisposable
Interface:If you were using un-managed resources, then the Dispose method is where you would ensure that those resources are properly released (the Garbage Collector will take care of all of your managed resources for you).
也许您应该看看这些 MSDN 文章:
Maybe you should take a look into these MSDN articles:
存在 dispose 方法,以便您可以释放已分配的任何非简单对象(通过垃圾收集清理)的资源。例如,
)都应该在您的 Dispose 方法中清理(可能通过在这些对象上调用 Dispose)。
如果您没有任何此类资源,则可能不需要实现 IDisposable。但是,您可能正在实现另一个继承自 IDisposable 的接口,例如 IEnumerator。在这种情况下,如果您没有上述任何资源,则可以将 Dispose 方法留空。
The dispose method is there so that you can release any resources that you have allocated that is not simple objects (which are cleaned up by garbage collection). For example
should be cleaned up in your Dispose method (probably by calling Dispose on those objects).
If you do not have any such resources, you probably do not need to implement IDisposable. However, you might be implementing another interface which inherits from IDisposable, such as IEnumerator. In that case you can leave the Dispose method empty if you don't have any of the resources mentioned above.
Dispose 的意思是释放非托管资源(即使用后不会被垃圾收集器自动处理的资源)。常见的示例是数据库和文件连接。 实现 Dispose 方法提供了更多说明和代码示例。
该页面有一个重要警告,即 Dispose 方法的实现方式应确保多次调用不会引发异常。这是因为它由垃圾收集器使用,并且可以多次调用 dispose 方法。
Dispose is meant to release unmanaged resources (i.e. resources that are not automatically taken care of by the garbage collector after use). Common examples are database and file connections. Implementing a Dispose Method provides more explanation and a code example.
That page has an important warning that the Dispose method should be implemented in such a way that multiple calls do not throw an exception. That's because it's used by the garbage collector and it can call the dispose method multiple times.
在 99% 的情况下,Microsoft 的框架过于复杂,而正确的方法很简单:
实现 IDisposable 的关键点不是清理任何特定类型的“资源”,而是确保如果某个对象以需要清理的方式更改了系统中的其他实体有时,这些实体将会被清理,而这样做所需的信息和动力仍然存在。理想情况下,清理工作应该尽快进行,但不能更早。例如,如果一个对象只包含一堆字符串数组,则不需要进行清理。字符串不需要任何清理;不需要清理的对象数组不需要任何清理,并且除了其他不需要清理的对象之外不包含任何内容的对象也不需要清理。另一方面,像打开 TCP 套接字这样的操作需要确保执行特定的清理操作(关闭套接字)。如果一个对象打开一个 TCP 套接字并保留有关它的信息,则对该对象调用 Dispose 的目的不是销毁有关套接字的信息(这将由垃圾收集器处理),而是确保必要的信息TCP 堆栈上的“关闭”操作被执行。
In 99% of cases, Microsoft's framework is vastly overcomplicated, and the right approach is simple:
The key point with implementing IDisposable isn't to clean up any particular kind of "resources", but rather to ensure that if an object changes other entities in the system in a way that needs to be cleaned up sometime, those entities will get cleaned up while the information and impetus necessary to do so still exists. Ideally, this cleanup should happen as soon as possible, but no sooner. If an object contains e.g. nothing but a bunch of arrays of strings, there will be no need for cleanup. A string does not require any cleanup; an array of objects not requiring cleanup does not require any cleanup, and an object holding nothing but other objects which don't require cleanup won't require cleanup either. On the other hand, an action like opening a TCP socket creates a need to ensure a certain cleanup action (closing the socket) will be performed. If an object opens a TCP socket and keeps information about it, the purpose of calling Dispose on that object wouldn't be to destroy the information about the socket (that will be taken care of by the garbage collector) but to ensure that the necessary "close" operation on the TCP stack gets performed.
MSDN 上有两篇相当不错的文章:实现 Dispose 方法 和 < a href="http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx" rel="nofollow">实现 Finalize 和 Dispose 来清理非托管资源。观察到第一条说:
我建议您阅读这两本书,决定是否需要实现它,并使用其中的代码示例作为开始。
There are two pretty decent articles on MSDN: Implementing a Dispose Method and Implementing Finalize and Dispose to Clean Up Unmanaged Resources. Having observed that the first one says:
I'd recommend you read both, decide whether you need to implement it, and use the code examples there as a start.
实现
IDisposable
1 只有两个原因,您在Dispose
方法中执行的操作取决于哪一个适用于您的情况。如果您的类创建了实现 IDisposable 的对象实例,并且无法在创建它们的方法中释放它们,则该类将具有引用这些实例的成员变量。该类还应该实现
IDisposable
,并且在其中您应该对每个一次性成员调用Dispose
。如果您直接使用非托管资源,您的类应该实现 IDisposable,并在其
Dispose
方法中根据需要处理它们。由于没有可用的标准接口,这到底意味着什么会有很大差异。这是非常不寻常的 - 通常您使用托管类来为您处理这些问题,例如FileStream
或SqlConnection
。 (在这种情况下,请参阅上文。)1除非您故意以非标准方式使用
IDisposable
。 (尽管其优点有争议。)There are only two reasons to implement
IDisposable
1 and what you do inside theDispose
method depends on which one applies to your situation.If your class creates object instances that implement
IDisposable
and cannot dispose of them in the method that creates them, that class will have member variables that reference those instances. That class should also implementIDisposable
, and inside it you should callDispose
on each disposable member.If you're using unmanaged resources directly, your class should implement
IDisposable
and in itsDispose
method you should deal with them as needed. What exactly that means will vary a lot, since there's no standard interface available. This is very unusual - normally you use managed classes that handle those for you, likeFileStream
orSqlConnection
. (In which case, see above.)1 Unless you're deliberately using
IDisposable
in a non-standard way. (Though the merits of that are debatable.)当您的类使用非托管系统资源(如文件句柄、指针)时,应使用 IDisposable 模式...以释放它们使用的内存。
如果您的类不使用非托管资源,则可能不需要使用此模式。
如果您确实需要 IDisposable :
The IDisposable pattern should be used when your class use unmanaged system resources, as handles on files, pointers... To free the memory they use.
If your class doesn't use unmanaged resources, it probably don't need to use this pattern.
If you really needs IDisposable :