C#2008
我一直在研究这个问题,我仍然对一些问题感到困惑.我的问题如下
我知道如果你处理非托管资源,你只需要一个终结器.但是,如果您使用托管资源来调用非托管资源,您是否仍需要实现终结器?
但是,如果您开发一个不直接或间接使用任何非托管资源的类,您是否可以实现IDisposable该类,以便您的类的客户端可以使用'using statement'?
是否可以接受实现IDisposable,以便您的类的客户端可以使用using语句?
using(myClass objClass = new myClass())
{
// Do stuff here
}
Run Code Online (Sandbox Code Playgroud)我在下面开发了这个简单的代码来演示Finalize/dispose模式:
public class NoGateway : IDisposable
{
private WebClient wc = null;
public NoGateway()
{
wc = new WebClient();
wc.DownloadStringCompleted += wc_DownloadStringCompleted;
}
// Start the Async call to find if NoGateway is true or false
public void NoGatewayStatus()
{
// Start the Async's download
// Do other work here
wc.DownloadStringAsync(new Uri(www.xxxx.xxx));
}
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
// …Run Code Online (Sandbox Code Playgroud)编辑:在Joel Coehoorns的优秀答案之后,我明白我需要更加具体,所以我修改了我的代码,使其更贴近我正在努力理解的事情......
事件:据我所知,在后台,事件是EventHandlers又名代表的"集合",将在事件引发时执行.所以对我来说,这意味着如果对象Y有事件E而对象X订阅事件YE,那么Y将引用X,因为Y必须执行位于X中的方法,这样就不能收集X,并且我理解的事情.
//Creates reference to this (b) in a.
a.EventHappened += new EventHandler(this.HandleEvent);
Run Code Online (Sandbox Code Playgroud)
但这不是Joel Coehoorn所说的......
但是,事件存在问题,有时人们喜欢将IDisposable与具有事件的类型一起使用.问题是当类型X订阅另一个类型Y中的事件时,X现在具有对Y的引用.该引用将阻止Y被收集.
我不明白X将如何引用Y ???
我修改了一些我的例子来说明我的情况更接近:
class Service //Let's say it's windows service that must be 24/7 online
{
A _a;
void Start()
{
CustomNotificationSystem.OnEventRaised += new EventHandler(CustomNotificationSystemHandler)
_a = new A();
B b1 = new B(_a);
B b2 = new B(_a);
C c1 = new C(_a);
C c2 = new C(_a); …Run Code Online (Sandbox Code Playgroud)