【发布时间】:2012-10-12 16:35:27
【问题描述】:
我有一些关于一次性课程的问题。假设我有一个 IDisposable 实现类,其中包含一些一次性成员。我已经实现了Dispose() 方法,即:
class BaseCustom: IDisposable
{
private System.Net.Sockets.TcpClient tc;
private System.Net.Sockets.NetworkStream ns;
public string str;
public int i;
public BaseCustom(string host, int port)
{
tc = new System.Net.Sockets.TcpClient(host, port);
ns = tc.GetStream();
}
// some other methods work on members (i, str, tc, ns)
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (ns != null)
{
ns.Close();
ns = null;
}
if (tc != null)
{
tc.Close();
tc = null;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
Q1) 既然没有非托管资源,那么压制finalizer可以吗? (在此处的代码中阅读note)
Q2) 既然我们处理了一次性成员并抑制了 GC,那么这里的 int 和 string 成员会发生什么?我们是否也需要处理它们?
Q3) 目前对tc 和ns 的释放是否正确?我看到不同版本的 .NET 引用中关于调用 Close() 与 Dispose() 的差异
现在假设我们有一个派生类:
class DerivedCustom : BaseCustom
{
public string cstr;
public int ci;
public DerivedCustom(string host, int port)
: base(host, port)
{}
// some extra methods
}
Q4)可能与Q2有关;我们需要在这里覆盖任何Dispose()s 吗?我们不会在派生类中引入任何非托管或一次性资源。保持原样是否安全(即信任基地的处置机制)?如果 GC 被抑制(它在派生中也被抑制,对吧),ci 和 cstr 会发生什么?同样与 Q1 相关,我们是否需要任何终结器?
Q5)如果基类是抽象类怎么办?
Q6)这很有趣;原样的代码没有给出关于 FxCop 1.36 中可处置性的任何警告。但是,如果我将一次性成员添加到 DerivedCustom 并且 仍然不覆盖一次性方法(因此不处理新成员),例如:
class DerivedCustom : BaseCustom
{
public string cstr;
public int ci;
// below is the only extra line
public System.Net.Sockets.TcpClient ctc = new System.Net.Sockets.TcpClient("ho.st", 1234);
public DerivedCustom(string host, int port)
: base(host, port)
{}
// some extra methods
}
在 FxCop 中仍然没有收到任何警告。这让我有点吃惊,因为处理 ctc 似乎没有得到妥善处理。
【问题讨论】:
标签: c# garbage-collection idisposable tcpclient