C#:实现IDisposable接口时Dispose方法的内容应该是什么

发布于 2024-10-18 02:04:01 字数 417 浏览 18 评论 0原文

我创建了一个实现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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

寻梦旅人 2024-10-25 02:04:01

我建议如何实施三个简单规则 I一次性;此处简化为:

  • 规则 1:不要这样做(除非需要)。只有两种情况需要实现 IDisposable:该类拥有非托管资源该类拥有托管资源(IDisposable )资源
  • 规则 2:对于拥有托管资源的类,实现 IDisposable(但不是终结器)。 IDisposable 的此实现应该只为每个拥有的资源调用 Dispose。该类不应该有终结器。
  • 规则 3:对于拥有单个非托管资源的类,同时实现 IDisposable 和终结器。

I recommend Three Simple Rules for how to implement IDisposable; simplified here:

  • Rule 1: Don't do it (unless you need to). There are only two situations when IDisposable does need to be implemented: The class owns an unmanaged resource or The class owns managed (IDisposable) resources.
  • Rule 2: For a class owning managed resources, implement IDisposable (but not a finalizer). This implementation of IDisposable should only call Dispose for each owned resource. The class should not have a finalizer.
  • Rule 3: For a class owning a single unmanaged resource, implement both IDisposable and a finalizer.
妥活 2024-10-25 02:04:01

除非您正在使用某种需要清理的非托管资源(在这个极其简单的情况下,您不需要清理),那么您确实没有理由实现 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:

The primary use of this interface is
to release unmanaged resources

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).

尝蛊 2024-10-25 02:04:01

存在 dispose 方法,以便您可以释放已分配的任何非简单对象(通过垃圾收集清理)的资源。例如,

  • 数据库连接和/或结果集
  • 指针指向非托管对象,
  • 您在对象内分配的任何对象(也实现 IDisposable

)都应该在您的 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

  • streams
  • database connections and/or result sets
  • pointers to unmanaged objects
  • any object you have allocated inside your object that is also implementing IDisposable

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.

旧人九事 2024-10-25 02:04:01

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.

清风夜微凉 2024-10-25 02:04:01

在 99% 的情况下,Microsoft 的框架过于复杂,而正确的方法很简单:

  1. 如果您的类具有实现 IDisposable 的任何类型字段,并且一旦您使用完这些对象,就没有人会期望使用它们,那么您应该实现 IDisposable,并且您的处置方法应该对所有此类字段调用 Dispose。
  2. 如果您的类没有这样的字段,但您认为从您的类派生的类可能没有这样的字段,或者如果您的类需要实现像 IEnumerator(of T) 这样需要 IDisposable 的接口,那么您应该有一个可重写的 Dispose 方法,该方法不执行任何操作。
  3. “dispose”方法的正确语义是让对象在被放弃之前执行任何必要的操作来清理其他对象。如果一个对象不需要清理其他对象,则 Dispose 不应该执行任何无害的操作。永远没有任何理由从 Dispose 抛出 NotImplementedException 或 NotSupportedException。

实现 IDisposable 的关键点不是清理任何特定类型的“资源”,而是确保如果某个对象以需要清理的方式更改了系统中的其他实体有时,这些实体将会被清理,而这样做所需的信息和动力仍然存在。理想情况下,清理工作应该尽快进行,但不能更早。例如,如果一个对象只包含一堆字符串数组,则不需要进行清理。字符串不需要任何清理;不需要清理的对象数组不需要任何清理,并且除了其他不需要清理的对象之外不包含任何内容的对象也不需要清理。另一方面,像打开 TCP 套接字这样的操作需要确保执行特定的清理操作(关闭套接字)。如果一个对象打开一个 TCP 套接字并保留有关它的信息,则对该对象调用 Dispose 的目的不是销毁有关套接字的信息(这将由垃圾收集器处理),而是确保必要的信息TCP 堆栈上的“关闭”操作被执行。

In 99% of cases, Microsoft's framework is vastly overcomplicated, and the right approach is simple:

  1. If your class has any fields of types that implement IDisposable, and nobody's going to expect to use those objects once you're done with them, you should implement IDisposable, and your disposal method should call Dispose on all such fields.
  2. If your class has no such fields, but you think classes that derive from yours might, or if your class needs to implement an interface like IEnumerator(of T) which requires IDisposable, you should have an overridable Dispose method that does nothing.
  3. The proper semantics for a "dispose" method is for an object to do whatever is necessary to clean up other objects before it is abandoned. If an object doesn't have to clean up other objects, Dispose should harmlessly do nothing. There is never any reason to throw NotImplementedException or NotSupportedException from Dispose.

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.

是你 2024-10-25 02:04:01

MSDN 上有两篇相当不错的文章:实现 Dispose 方法 和 < a href="http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx" rel="nofollow">实现 Finalize 和 Dispose 来清理非托管资源。观察到第一条说:

在仅使用托管资源(例如数组)的类型上实现 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:

There is no performance benefit in implementing the Dispose method on types that use only managed resources (such as arrays) because they are automatically reclaimed by the garbage collector.

I'd recommend you read both, decide whether you need to implement it, and use the code examples there as a start.

清旖 2024-10-25 02:04:01

实现 IDisposable1 只有两个原因,您在 Dispose 方法中执行的操作取决于哪一个适用于您的情况。

如果您的类创建了实现 IDisposable 的对象实例,并且无法在创建它们的方法中释放它们,则该类将具有引用这些实例的成员变量。该类还应该实现IDisposable,并且在其中您应该对每个一次性成员调用Dispose

如果您直接使用非托管资源,您的类应该实现 IDisposable,并在其 Dispose 方法中根据需要处理它们。由于没有可用的标准接口,这到底意味着什么会有很大差异。这是非常不寻常的 - 通常您使用托管类来为您处理这些问题,例如FileStreamSqlConnection。 (在这种情况下,请参阅上文。)

1除非您故意以非标准方式使用 IDisposable。 (尽管其优点有争议。)

There are only two reasons to implement IDisposable1 and what you do inside the Dispose 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 implement IDisposable, and inside it you should call Dispose on each disposable member.

If you're using unmanaged resources directly, your class should implement IDisposable and in its Dispose 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, like FileStream or SqlConnection. (In which case, see above.)

1 Unless you're deliberately using IDisposable in a non-standard way. (Though the merits of that are debatable.)

莳間冲淡了誓言ζ 2024-10-25 02:04:01

当您的类使用非托管系统资源(如文件句柄、指针)时,应使用 IDisposable 模式...以释放它们使用的内存。

如果您的类不使用非托管资源,则可能不需要使用此模式。

如果您确实需要 IDisposable :

public void Dispose()
{
  //Free here your resources

  this.Dispose(true);
  GC.SuppressFinalize(this);
}

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 :

public void Dispose()
{
  //Free here your resources

  this.Dispose(true);
  GC.SuppressFinalize(this);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文