I believe this snippet:
<snip>
try
{
Encoding ASCII = Encoding.ASCII;
IPEndPoint hostEndPoint;
IPAddress hostAddress = System.Net.IPAd dress.Loopback;
int conPort = port;
string Get = "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nCo nnection:
Close\r\n\r\n";
Byte[] ByteGet = ASCII.GetBytes( Get);
byte[] RecvBytes = new byte[256];
hostEndPoint = new IPEndPoint(host Address, conPort);
Socket s= new Socket(AddressF amily.InterNetw ork, SocketType.Stre am,
ProtocolType.Tc p);
s.Connect(hostE ndPoint);
s.Send(ByteGet, ByteGet.Length, 0);
s.Close();
}
catch
{
}
</snip>
could be changed to:
<NewSnip>
Encoding ASCII = Encoding.ASCII;
IPEndPoint hostEndPoint;
IPAddress hostAddress = System.Net.IPAd dress.Loopback;
int conPort = port;
Byte[] ByteGet = ASCII.GetBytes( "GET / HTTP/1.1\r\nHost:
127.0.0.1\r\nCo nnection: Close\r\n\r\n") ;
byte[] RecvBytes = new byte[256];
hostEndPoint = new IPEndPoint(host Address, conPort);
using (Socket s= new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p))
{
s.Connect(hostE ndPoint);
s.Send(ByteGet, ByteGet.Length, 0);
s.Shutdown();
// shouldn't need to call close explicitly; Dispose should handle this
// note that by using the using construct, Dispose is called.
}
</NewSnip>
The main reason you should implement IDispose in one of your own classes
is to ensure that unmanaged resources (Database connections is the
classic example) are released.
You might find this template helpful:
<ClassImplement ingDispose>
class Billy: IDisposable
{
private bool mDisposed = false;
public void doStuff()
{
// do this in each public method in case user called dispose,
// but then tried to call another method
if ( mDisposed ) throw new ObjectDisposedE xception();
// do what you normally do.
}
/// <summary>
/// If SupressFinalize wasn't there, the gc would have to do all the
/// extra work that is required for objects in the finalization queue.
/// </summary>
public void Dispose()
{
Dispose( true );
GC.SuppressFina lize(this);
}
protected virtual void Dispose( bool disposing )
{
if ( disposing )
{
// dispose any dependant managed objects if necessary.
// You don't want this to happen when the GC is calling this code
// because you have no idea what state other objects would be in at
that point.
disposed = true;
}
// Free unmanaged resources here.
}
~Billy()
{
Dispose( false );
Debug.Assert(fa lse, "You are using this object improperly. Create in
using construct or ensure to call Dispose()");
}
}
</ClassImplementi ngDispose>
André wrote:
Thanks Kevin,
Can you help me add the dispose interface?
This is my simple ping class......