TcpClient を使用するクラスにファイナライザーを実装する必要がありますか?
-
23-08-2019 - |
質問
私はクラスを持っています(言う) MyClass
) を使用します (プライベートフィールドとして持っています) TcpClient
物体。 MyClass
実装する IDisposable
電話をかける TcpClient.Close
の中に Dispose
方法。
私の質問はそうすべきです MyClass
呼び出すファイナライザーも実装します Dispose(bool Disposing)
を解放する TcpClient’s
万が一に備えて管理されていないリソース MyClass.Dispose
呼び出しコードによって呼び出されないのでしょうか?
ありがとう
解決
ないと思います。
ので るわけにはゆきませんメソッドの呼び出し、その他のオブジェクトfinalizer, することによって確定前にオブジェクトです。
のfinalizerの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が同時に死んでいると思われる2つのオブジェクトがある場合、どのファイナイザーが最初に完了するかを予測することはできません。これは、インスタンス変数に保存されているファイナライズ可能なオブジェクトと対話するファイナルイザーを持つことができないことを意味します。
これは、使い捨て/ファイナライズ パターンの私のリファレンス実装であり、いつ何を使用するかを説明するコメントが付いています。
/// <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時にオフィスに呼ばれることは決してありません覚えています