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)我认为以前没有问过这个问题.我IDisposable对在密封类上实现的最佳方法感到困惑- 特别是一个不从基类继承的密封类.(也就是说,这是一个"纯密封的类",这是我的术语.)
也许你们有些人同意我的观点,因为实施指南IDisposable非常混乱.也就是说,我想知道我打算实施的方式IDisposable是充分和安全的.
我正在做一些P/Invoke代码,分配一个IntPtr通过Marshal.AllocHGlobal,自然,我想干净地处理我创建的非托管内存.所以我在考虑这样的事情
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public sealed class MemBlock : IDisposable
{
IntPtr ptr;
int length;
MemBlock(int size)
{
ptr = Marshal.AllocHGlobal(size);
length = size;
}
public void Dispose()
{
if (ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(ptr);
ptr = IntPtr.Zero;
GC.SuppressFinalize(this);
}
}
~MemBlock()
{
Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
我假设因为MemBlock完全是密封的,并且永远不会从另一个实现a的类中派生出来virtual protected Dispose(bool disposing).
那么,终结者是否必须?欢迎所有的想法.