I believe this snippet:
<snip>
try
{
Encoding ASCII = Encoding.ASCII;
IPEndPoint hostEndPoint;
IPAddress hostAddress = System.Net.IPAddress.Loopback;
int conPort = port;
string Get = "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection:
Close\r\n\r\n";
Byte[] ByteGet = ASCII.GetBytes(Get);
byte[] RecvBytes = new byte[256];
hostEndPoint = new IPEndPoint(hostAddress, conPort);
Socket s= new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
s.Connect(hostEndPoint);
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.IPAddress.Loopback;
int conPort = port;
Byte[] ByteGet = ASCII.GetBytes("GET / HTTP/1.1\r\nHost:
127.0.0.1\r\nConnection: Close\r\n\r\n");
byte[] RecvBytes = new byte[256];
hostEndPoint = new IPEndPoint(hostAddress, conPort);
using (Socket s= new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp))
{
s.Connect(hostEndPoint);
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:
<ClassImplementingDispose>
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 ObjectDisposedException();
// 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.SuppressFinalize(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(false, "You are using this object improperly. Create in
using construct or ensure to call Dispose()");
}
}
</ClassImplementingDispose>
André wrote:
Thanks Kevin,
Can you help me add the dispose interface?
This is my simple ping class......