需要实行一个终结在一类使用的TcpClient?
-
23-08-2019 - |
题
我有一个类(说 MyClass
)使用(有作为一个私人领域)一个 TcpClient
对象。 MyClass
实现了 IDisposable
叫 TcpClient.Close
在 Dispose
法。
我的问题是应该 MyClass
还实行一个终结的呼叫 Dispose(bool Disposing)
免费的 TcpClient’s
不受管理的资源的情况下 MyClass.Dispose
不是所谓的呼叫代码?
感谢
解决方案
不,你不应该。
由于你永远不应该在终结调用的方法的其他物体上,它可能是你的对象之前完成。
您的TcpClient的终结将被垃圾收集器调用,所以让他做。
在处置模式是:
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// dispose managed resources (here your TcpClient)
}
// dispose your unmanaged resources
// handles etc using static interop methods.
}
其他提示
不,你不应该。
从 此 优秀的员额:
最后确定是从根本上 不同结束的一个目的 生。从正点的 看来,没有订购之间 终结器(外的一种特殊情况 对于关键的终结器),因此,如果您 有两种对象的GC认为 是死在同一时间,你不能 预测哪终结会完成 第一次。这意味着你不能有一个 终结,与任何 终结的对象的存在实例 变量。
这是我的参考执行情况的一次性/定稿案的评论说明时使用了什么:
/// <summary>
/// Example of how to implement the dispose pattern.
/// </summary>
public class PerfectDisposableClass : IDisposable
{
/// <summary>
/// Type constructor.
/// </summary>
public PerfectDisposableClass()
{
Console.WriteLine( "Constructing" );
}
/// <summary>
/// Dispose method, disposes resources and suppresses finalization.
/// </summary>
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes resources used by class.
/// </summary>
/// <param name="disposing">
/// True if called from user code, false if called from finalizer.
/// When true will also call dispose for any managed objects.
/// </param>
protected virtual void Dispose(bool disposing)
{
Console.WriteLine( "Dispose(bool disposing) called, disposing = {0}", disposing );
if (disposing)
{
// Call dispose here for any managed objects (use lock if thread safety required), e.g.
//
// if( myManagedObject != null )
// {
// myManagedObject.Dispose();
// myManagedObject = null;
// }
}
}
/// <summary>
/// Called by the finalizer. Note that if <see cref="Dispose()"/> has been called then finalization will
/// have been suspended and therefore never called.
/// </summary>
/// <remarks>
/// This is a safety net to ensure that our resources (managed and unmanaged) are cleaned up after usage as
/// we can guarantee that the finalizer will be called at some point providing <see cref="Dispose()"/> is
/// not called.
/// Adding a finalizer, however, IS EXPENSIVE. So only add if using unmanaged resources (and even then try
/// and avoid a finalizer by using <see cref="SafeHandle"/>).
/// </remarks>
~PerfectDisposableClass()
{
Dispose(false);
}
}
不,你不必。 TcpClient的是周围的非托管的插座,在那里它被管理的,应当设置在道路的包装类。您所做的一切就足够了。
是的,你应该 - 微软甚至建议将它一>
只要记住,皮带和吊带代码永远不会被你叫进办公室在2:00 AM:)
不隶属于 StackOverflow