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)我对CLR和GC的工作方式很着迷(我正在通过C#,Jon Skeet的书籍/帖子等阅读CLR来扩展我的知识).
无论如何,说:有什么区别:
MyClass myclass = new MyClass();
myclass = null;
Run Code Online (Sandbox Code Playgroud)
或者,通过使MyClass实现IDisposable和析构函数并调用Dispose()?
另外,如果我有一个带有using语句的代码块(例如下面的代码),如果我单步执行代码并退出using块,那么对象是在处理垃圾收集时发生的吗?如果我在使用块中调用Dispose()会发生什么?
using (MyDisposableObj mydispobj = new MyDisposableObj())
{
}
Run Code Online (Sandbox Code Playgroud)
流类(例如BinaryWriter)有一个Finalize方法吗?我为什么要用它?